2

I am looking for the same solution that was found in this question: How can I import an RSA private key into an RSACryptoServiceProvider?

Unfortunately the actual method of the solution is not provided and I'm having trouble with the last steps. The overview:

I have an existing private key that was creating with CAPI using these steps:

// Abbreviated for clarity.
CryptAcquireContext(..., MS_ENHANCED_PROV, ...);

// Generate public/private key pair

CryptCreateHash(..., CALG_SHA1, ...);
CryptHashData(hash, password, ...);
CryptDeriveKey(..., CALG_3DES, hash, CRYPT_EXPORTABLE, ...);
CyrptExportKey(..., derivedKey, PRIVATEKEYBLOB, ...);

I need to import this key into a C# RSACryptoService provider.

Based on the other question, I know that I have to derive the key using PasswordDerivedBytes and then decrypt the key using the derived key, but I do not know how to perform those steps.

I've got something like the following to get started:

var parameters = new CspParameters
{
    ProviderName = "Microsoft Enhanced Cryptographic Provider v1.0",
    ProviderType = 1, 
    Flags = CspProviderFlags.UseMachineKeyStore, 
    KeyContainerName = "KeyContainer"
};

var csp = new RSACryptoServiceProvider(parameters);
byte[] pwd = Encoding.ASCII.GetBytes("Password");

PasswordDeriveBytes pdb = new PasswordDeriveBytes(pwd, new byte[0], parameters);
// This line throws a CryptographicException with "Invalid flags specified."
byte[] symKey = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, new byte[8]);

If I remove the KeyContainerName from the CspParamaters then I can generate a key, but I was under the impression that I had to use the same Csp to derive the same key.

And once I've got the key out, I don't know what I'm supposed to do with it to decrypt the key.

Community
  • 1
  • 1
Ben Randall
  • 1,205
  • 10
  • 27
  • This question is hard to answer if we don't know exactly how the password protected private key has been generated and which format it is in now. – Maarten Bodewes Jan 18 '14 at 11:42
  • The password protected key was generated in Native code using the CAPI stuff at the top of my question. SHA1, 3DES, etc. Is there something specific that is missing that you're looking for? – Ben Randall Feb 07 '14 at 00:36
  • You still seem to use `PasswordDeriveBytes`. It was - correctly in my opinion - suggested not to use that function. `PasswordDeriveBytes` implements PBKDF1, that function relies on a hash function, but it won't generate identical output for the wrapping key. You should try and create identical symmetric wrapping functions on both sides. So either use PBKDF1 on both sides (or PBKDF2 if it's available) or a hash. Take things step by step, print out the intermediate results in hex to compare. – Maarten Bodewes Feb 07 '14 at 09:08

0 Answers0