I am creating a little tool for encrypt and decrypt using a pair keys (public and private keys). I export public and private key on my computer and I can encrypt and decrypt files without problems. I have problem when I try decrypt files in other machine with the same public key.
// initializing CSP HCRYPTPROV hProv; HCRYPTKEY hKey;
if(!CryptAcquireContext(hProv, NULL, NULL, PROV_RSA_FULL, 0)){ if(GetLastError() == NTE_BAD_KEYSET){ if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)){ return FALSE; } } }
// create a pair keys if (!CryptGenKey(hProv, AT_KEYEXCHANGE, CRYPT_ARCHIVABLE, &hKey)) return FALSE;
// public key if (!CryptExportKey(hKey, 0, PUBLICKEYBLOB, 0, NULL, sizePublicKey)) return FALSE;
*publicKey = (BYTE *) LocalAlloc(LPTR, *sizePublicKey * sizeof(DWORD)); if(*publicKey == NULL) return FALSE;
if (!CryptExportKey(hKey, 0, PUBLICKEYBLOB, 0, *publicKey, sizePublicKey)) return FALSE; // save public key on file
// private key if (!CryptExportKey(hKey, 0, PRIVATEKEYBLOB, 0, NULL, sizePrivateKey)) return FALSE;
*privateKey = (BYTE *) LocalAlloc(LPTR, *sizePrivateKey * sizeof(DWORD)); if(*publicKey == NULL) return FALSE;
if (!CryptExportKey(hKey, 0, PRIVATEKEYBLOB, 0, *privateKey, sizePrivateKey)) return FALSE;
PrivateKey.key = (BYTE *) LocalAlloc(LPTR, *sizePrivateKey * sizeof(DWORD)); if(*publicKey == NULL) return FALSE; // save private key on file
//I encrypt file using if(!CryptEncrypt(hKey, 0, TRUE, 0, cache, &sizeCache, BLOCK_SIZE_ENCRYPT)){
free(cache);
return FALSE; }
//To decrypt file //First import public key
CryptImportKey(hProv, publicKey, sizePublicKey, 0, 0, &hKey)
//To decrypt: if (!CryptDecrypt(hKey, 0, TRUE, 0, cache, &sizeCache)){
free(cache);
return FALSE; }
In the same computer that key ware created the application encrypt and decrypt correctly but if I try decrypt files in other computer the CryptDecrypt() failed with error 80090003 (error got by GetLastError()) Any idea? what am I doing wrong...? How to I can export the public key to other computer? Thanks!