Decrypt using a non-exportable private key with CryptoAPI

991 views Asked by At

I created RSA key pair in windows key store.

I encrypted data (a symmetric key) successfully:

HCERTSTORE hstore = ::CertOpenSystemStore(NULL, L"TestStore");
PCCERT_CONTEXT pctxt = ::CertFindCertificateInStore(hstore, X509_ASN_ENCODING, NULL, 

CERT_FIND_SUBJECT_STR, L"My Test Keys", NULL);

HCRYPTPROV hprovider = NULL;
if(!::CryptAcquireContext(&hprovider,
            NULL,
            MS_ENHANCED_PROV,
            PROV_RSA_FULL,
                    NULL/*CRYPT_NEWKEYSET*/))
{
   DWORD err = ::GetLastError();
   return 0;
}

HCRYPTKEY hkey = NULL;
if(!::CryptImportPublicKeyInfo(hprovider, 
                X509_ASN_ENCODING,
                &pctxt->pCertInfo->SubjectPublicKeyInfo,
                &hkey
                ))
{
   return 0;
}

Now I used CryptEncrypt() with HCRYPTKEY.


Next I want to decrypt the data with the private key, but it is not exportable. All the examples I've seen include importing of the keys.

How can I decrypt the data without exporting the key?

1

There are 1 answers

0
Mauricio Sadicoff On

Well, I'm not an expert in RSA/Microsoft store, but I think I get what you're trying to do here. You're doing it a bit backwards. You're using the public key to encrypt and the private do decrypt. So the assumption is that you'd have the private key since that is what you used to generate the public key.

So, let's see... to decrypt the data you need a key, right? So you can (a) encrypt the data with the public key and then find a way to export the private key, but then you'd be using something akin to private key encryption and you'd be better off using blowfish anyway, or (b) encrypt the data using your private key so that you can share the public key to decrypt. Remember CryptImportPublicKeyInfo returns a handle to it: http://msdn.microsoft.com/en-us/library/windows/desktop/aa380209(v=vs.85).aspx

So what I'm saying is that you already have your answer. It's there when you say you have a symmetric key. Either you'll use the same public key to decrypt or it will be a simple transformation: http://en.wikipedia.org/wiki/Symmetric-key_algorithm