0

I've created a RSA key with NCryptCreatePersistedKey and then later I want to use the NCryptExportKey to export its public key into a blob then write out into a file (DER or PEM doesnt matter). I've tried with this sample:

NCryptExportKey(
    keyHandle, 
    NULL,
    BCRYPT_RSAPUBLIC_BLOB, // blob type
    NULL,
    NULL,
    0,
    &keyBlobLength,
    0);
    
keyBlob = (PBYTE)HeapAlloc(
    GetProcessHeap(),
    0,
    keyBlobLength);
    
NCryptExportKey(
    keyHandle,
    NULL,
    BCRYPT_RSAPUBLIC_BLOB,  // blob type
    NULL,
    keyBlob,
    keyBlobLength,
    &keyBlobLength,
    0);
    
QByteArray array((const char*)keyBlob, (int)keyBlobLength);
QFile file("public.key");
file.open(QIODevice::WriteOnly);
file.write(array);
file.close();

It seems that the written file having the keyBlob content is not a valid public key:

openssl rsa -pubin -in public.key -inform DER -outform PEM -out public.key.pem
unable to load Public Key
13692:error:0D0680A8:asn1 encoding routines:asn1_check_tlen:wrong tag:crypto\asn1\tasn_dec.c:1149:
13692:error:0D07803A:asn1 encoding routines:asn1_item_embed_d2i:nested asn1 error:crypto\asn1\tasn_dec.c:309:Type=X509_PUBKEY

openssl rsa -RSAPublicKey_in -in public.key -inform DER -outform PEM -out public.key.pem -RSAPublicKey_out
unable to load Public Key
27084:error:0D0680A8:asn1 encoding routines:asn1_check_tlen:wrong tag:crypto\asn1\tasn_dec.c:1149:
27084:error:0D07803A:asn1 encoding routines:asn1_item_embed_d2i:nested asn1 error:crypto\asn1\tasn_dec.c:309:Type=RSAPublicKey

I've tried with several blob types without success.

When I exported the private key, using the NCRYPT_PKCS8_PRIVATE_KEY_BLOB blob type, that was successful, had a valid private key in the file.

I've read that Microsoft BLOB data uses the little endian data representation, while openssl the big endian: https://stosd.wordpress.com/2017/04/22/capi-openssl/ But there is a common datatype which both supports: PKCS #8. Maybe this is the reason why the private key export worked fine when I used the NCRYPT_PKCS8_PRIVATE_KEY_BLOB type ???

Can somebody provide me a code example how to export a public key with NCryptExportKey and then write out into a file which then is compatible with openssl ? Or to confitm that the reason why I cannot export a public key into a file is because of that big-endian, little-endian presentation difference.

wildfrontier
  • 25
  • 1
  • 6

0 Answers0