如何在WinCrypt中生成和使用公钥加密 [英] How to generate and use public key cryptography in WinCrypt
问题描述
我目前正在尝试Windows密码API,并且遇到了公钥密码的一些问题。我可以找到许多有关如何加密项目的示例,但是没有什么可以直接解决从头到尾的公钥模型。
I'm currently experimenting with the Windows Cryptography API and running into some problems with Public-Key-Cryptography. I can find lots of examples of how to encrypt items, but nothing directly addressing a start-to-finish public key model.
以下是我当前代码的粗略概述看起来会生成一个加密密钥对,我已经删除了错误检查代码,以提高可读性
Here's a rough outline of how my current code looks to generate an encryption key pair, I've removed the error checking code for readability
// 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();
我的两个导出密钥不同,但是两个都可以解密消息而无需加载另一个密钥。另外,如果我在加载导出的公共密钥的新会话中对新消息进行加密,我仍然可以使用其中任何一个密钥对其进行解密。
My two exported keys are different, but both are able to decrypt message without the other key being loaded. Additionally, if I encrypt a new message in a new session that loads the exported public key, I can still decrypt it with either key.
有人可以建议我可能做错了或丢失了?我是在完全错误的路径上吗?
Can anyone advise me on what I might be doing wrong or missing? Am I on completely the wrong path?
推荐答案
您是否在两个键上都使用了CryptImportKey?看起来您的加密只是使用生成的密钥的句柄。要正确地进行公钥/私钥对,您应该仅使用CryptExportKey导出公钥,并将其提供给需要的人。尽管这不是真正的加密,但它是该人知道来自您的一种方式。
Are you using CryptImportKey on both keys? It looks like your encrypt is just using the handle to thekey you generated. To do Public/Private pairs correctly you should export just the public key with CryptExportKey and give it to whomever needs it. Although this isn't true "encryption" its a way for that person to know it is from you.
这篇关于如何在WinCrypt中生成和使用公钥加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!