我目前正在尝试使用 Windows Cryptography API 并遇到一些 Public-Key-Cryptography 问题。我可以找到很多关于如何加密项目的示例,但没有直接解决从头到尾的公钥模型。
这是我当前代码如何生成加密密钥对的粗略概述,为了便于阅读,我删除了错误检查代码
// MAKE AN RSA PUBLIC/PRIVATE KEY:
CryptGenKey(hProv, CALG_RSA_KEYX, CRYPT_EXPORTABLE, &hKey);
// NOW LET'S EXPORT THE PUBLIC KEY:
DWORD keylen;
CryptExportKey(hKey,0,PUBLICKEYBLOB,0,NULL,&keylen);
LPBYTE KeyBlob;
KeyBlob = (LPBYTE)malloc(keylen);
CryptExportKey(hKey,NULL,PUBLICKEYBLOB,0,KeyBlob,&keylen);
ofstream outputkey;
outputkey.open("TestPublicKey.txt", ios_base::out | ios_base::binary);
for(size_t i=0; i < keylen; ++i)
outputkey<<KeyBlob[i];
outputkey.close();
free(KeyBlob);
// NOW LET'S EXPORT THE PRIVATE KEY:
CryptExportKey(hKey, 0, PRIVATEKEYBLOB,0,NULL,&keylen);
KeyBlob = (LPBYTE)malloc(keylen);
CryptExportKey(hKey,NULL,PRIVATEKEYBLOB,0,KeyBlob,&keylen)
outputkey.open("TestPrivateKey.txt", ios_base::out | ios_base::binary);
for(size_t i=0;i<keylen;++i)
outputkey<<KeyBlob[i];
outputkey.close();
free(KeyBlob);
// ENCRYPT A (SHORT) TEST MESSAGE [SHOULD JUST BE ANOTHER ALG'S KEY LATER]:
DWORD encryptBufferLen=0;
CryptEncrypt(hKey, 0, true, 0, NULL, &encryptBufferLen, 0); // how much space?
BYTE* encryptionBuffer = (BYTE*)malloc(encryptBufferLen);
memcpy(encryptionBuffer, TestMessage, TestMessageLen); // move for in-place-encrypt
CryptEncrypt(hKey,0,true,0, encryptionBuffer, &bufferlen, encryptBufferLen );
ofstream message;
message.open("Message.txt", ios_base::out | ios_base::binary);
for(size_t i=0;i<encryptBufferLen;++i)
message<<encryptionBuffer[i];
message.close();
我的两个导出密钥不同,但都能够在不加载另一个密钥的情况下解密消息。此外,如果我在加载导出的公钥的新会话中加密新消息,我仍然可以使用任一密钥对其进行解密。
谁能告诉我我可能做错了什么或错过了什么?我完全走错了路吗?