在其他计算机上导入RSA密钥的问题

Problems to import RSA key in other computer

本文关键字:密钥 问题 RSA 导入 其他 计算机      更新时间:2023-10-16

我正在创建一个使用一对密钥(公钥和私钥)进行加密和解密的小工具。我在我的电脑上导出公钥和私钥,我可以加密和解密文件没有问题。当我尝试用相同的公钥解密其他机器中的文件时,我遇到了问题。

// 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;           }

在同一台计算机上,密钥软件创建了应用程序加密和解密正确,但如果我试图解密其他计算机上的文件,CryptDecrypt()失败,错误80090003 (GetLastError()获得的错误)任何想法?我做错了什么?如何将公钥导出到其他计算机?谢谢!

可能您没有导出密钥,只是使用包含密钥的CSP,而您在同一台计算机中,密钥存储在您使用cryptoapi"链接"的容器中。当你转到另一台计算机时,容器不存在,所以你不能使用这个密钥。

确保私钥是可导出的