0

Using windows CryptoAPI, is it possible to get public RSA key from a private key which was imported (not generated)?

If I use CryptGenKey, I can call CryptExportPublicKeyInfo and CryptImportPublicKeyInfo to obtain the public key handle. However, when I try to do the same thing with private key decoded from PEM and imported using:

CryptImportKey(hCSP, pKeyBuf, cbKeyBuf, 0, CRYPT_EXPORTABLE, &hPrivKey)

import of the private key succeeds and I have a valid handle but the subsequent call to CryptExportPublicKeyInfo fails with "Key does not exist" error. It looks like there's another call missing between CryptImportKey and CryptExportPublicKeyInfo, but I can not find that API call.

Alex
  • 5,159
  • 4
  • 25
  • 33
  • What does your `CryptExportPublicKey` call look like? Is it a signature key or a key encryption key? – erickson Feb 24 '15 at 17:05
  • The PEM being imported was generated by calling CryptExportKey(hKey, 0, PRIVATEKEYBLOB, 0, &buf, &size) and buf then encoded into DER -> PEM. I can successfully import private key from the PEM but don't know how to get public key out of it. – Alex Feb 24 '15 at 18:29
  • I'm talking about the "subsequent call" that fails, not the origin of the private key. Does the second export look the same as the original export? I am not familiar with the CryptoAPI, but other APIs that I know well offer an API to give you a "transparent" view of key material. In the case of an RSA private key, that would generally give you a structure representing the key in Chinese Remainder Theorem form (CRT), which would have a number of large integer members. I didn't see anything like that skimming quickly over the Windows CryptoAPI docs. Does that ring a bell? – erickson Feb 24 '15 at 18:59
  • Thanks for your interest in this question, I figured it out (see the [code](https://gist.github.com/aleks-f/21d8ebf5547e17e71c92)) and I'm able to move on with work but it is still not 100% clear to me why CryptExportPublicKeyInfo()/CryptImportPublicKeyInfo() does not work. – Alex Feb 25 '15 at 02:23

1 Answers1

1

The problem with exporting/importing the public key was because private key was generated using AT_SIGNATURE, instead of AT_EXCHANGE. See the explanation and the example code

Alex
  • 5,159
  • 4
  • 25
  • 33