3

I have a doubt related to CryptExportKey and CryptImportKey. I will try my best to define my problem by explaining the scenario that I want to implement.

I have two machines. On First machine, I create a Key-pair using CryptGenKey with ALGID=ALG_SID_RSA_PKCS then I exported the key using CryptExportKey with PUBLICKEYBLOB flag. I then send the blob to the second machine over the network. On first machine I then encrypt the file using CryptEncrypt with the same key (created previously with CryptGenKey). After encrypting the file, I send this file to the second machine.

So on second machine, I have key blob and the encrypted file. Now, I want to decrypt the file on second machine, using key blob.

On Second Machine, I am trying to import the key blob using CryptImportKey, it returns successfully but when calling CryptDecrypt, it gives an error 08009000d (NTE_NO_KEY, key doesn't exist).

Is it possible to decrypt the file on second machine.

Thanks in advance.

1 Answers1

3

You are using an asymmetric encryption algorithm. By design of this, only the party that has the private key can decipher, and in your case that's the first machine only, because you exported the public key; this explains why you fail to decipher on the second machine.

There are at least two good options to fix this:

  • Encipher on the second machine, and decipher on the first machine; but you must somewhat manage that the public key is not altered during transfer to the second machine (which is not implied by "send the blob to the second machine over the network").
  • Generate the key (pair) on the second machine, export the public key and send it to the first machine, with similar requirements that it is not altered in transfer.

If your use case is to encipher (that is, protect the confidentiality of a message) on the machine that generated the key, then it is pointless that this key is for an asymmetric cryptosystem like RSA (a symmetric cryptosystem like AES will do), and you must somewhat manage to move the deciphering key to the deciphering machine in a way that protects that key's confidentiality (which is not implied by "send the blob to the second machine over the network", and typically is harder to achieve that ensuring that the key is not altered).

If your use case is to sign (that is, demonstrate origin and integrity of a message, in such a way that the check requires no confidential material), then generating the key pair on the machine that signs the message and exporting the public key is correct, but you still must somewhat manage that the public key is not altered during transfer to the second machine.

fgrieu
  • 149,326
  • 13
  • 324
  • 622