问题描述
我有一个生成的RSA密钥对,存储为PRIVATEKEYBLOB和PUBLICKEYBLOB,我需要能够将这些密钥转换为DER或PEM格式,以便可以在PHP或Python中使用它。我发现可以使用CryptEncodeObject函数将PRIVATEKEYBLOB转换为DER。为此,我需要使用PKCS_RSA_PRIVATE_KEY编码标志。但是我找不到有关如何将PUBLICKEYBLOB转换为DER的任何线索。
I have a generated RSA key pair stored as PRIVATEKEYBLOB and PUBLICKEYBLOB, and I need to be able to convert these keys to DER or PEM formats so I could use it in PHP or Python. I figured out that I could use CryptEncodeObject function to convert my PRIVATEKEYBLOB to DER. In order to do that I need to use PKCS_RSA_PRIVATE_KEY encoding flag. But I couldn't find any clue on how to convert PUBLICKEYBLOB to DER.
这是我的PRIVATEKEYBLOB转换代码:
Here is my code for PRIVATEKEYBLOB convertion:
LPCSTR type = PKCS_RSA_PRIVATE_KEY;
DWORD encd = X509_ASN_ENCODING | PKCS_7_ASN_ENCODING;
DWORD dlen = 0;
if(!CryptEncodeObject(encd, type, key, null, &dlen))
{ LOG_ERROR(); return false; }
// Buffer allocation (der variable)
if(!CryptEncodeObject(encd, type, key, der, &dlen))
{ LOG_ERROR(); return false; }
我通过将密钥与openssl工具的输出进行比较来测试密钥:
I test my keys by comparing them to the output of openssl tool:
openssl rsa -pubin -inform MS\ PUBLICKEYBLOB -in pub.ms -outform DER -out pub.der
openssl rsa -inform MS\ PRIVATEKEYBLOB -in pri.ms -outform DER -out pri.der
添加:我尝试使用RSA_CSP_PUBLICKEYBLOB与X509_ASN_ENCODING一起使用,但结果与openssl工具的输出不同,并且密钥导入失败。 openssl导出的DER长25个字节,两个键中只有前3个字节相等。这是关键比较的图片:
ADDED: I tried RSA_CSP_PUBLICKEYBLOB with X509_ASN_ENCODING, but the result is different to the output of openssl tool, and the key import failes. The openssl's exported DER is 25 bytes longer, and only first 3 bytes are equal in both keys. Here is the picture of key comparison:
如果仔细观察这张图片,我们可以看到openssl的密钥版本在第3个字节之后还有某种额外的24个字节的标头。到目前为止,还没有弄清楚它是什么,但是如果我用从RSA_CSP_PUBLICKEYBLOB的CryptEncodeObject获得的输出来将这个硬编码的标头隐藏起来,则一切正常。不确定该标头是否始终相同。
If we look closely at this picture, we can see that openssl's key version has some kind of additional 24 bytes header after the 3rd byte. Haven't figured out what is it as of yet, but if I concatinate this hardcoded header with the output I get from CryptEncodeObject with RSA_CSP_PUBLICKEYBLOB it all works fine. Not sure if that header is always the same or not though.
推荐答案
使用RSA_CSP_PUBLICKEYBLOB,如
Use RSA_CSP_PUBLICKEYBLOB as documented inhttps://msdn.microsoft.com/en-us/library/windows/desktop/aa378145(v=vs.85).aspx
这篇关于Microsoft CryptoAPI:如何将PUBLICKEYBLOB转换为DER / PEM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!