The simple blob that is generated using
CryptExportKey(hKey, hPublicKey, SIMPLEBLOB, 0, lpData, &nSize);
does not match the one generated from the following code (note that client.key is the plain text key value of hKey found using http://www.codeproject.com/KB/security/plaintextsessionkey.aspx )
CspParameters cspParams = new CspParameters();
cspParams.KeyContainerName = "Container Name";
cspParams.KeyNumber = (int)KeyNumber.Exchange;
cspParams.ProviderType = 1;
cspParams.ProviderName = "Microsoft Enhanced Cryptographic Provider v1.0"; cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
RSACryptoServiceProvider rsaClient = new RSACryptoServiceProvid(cspParams);
rsaClient.ImportCspBlob(File.ReadAllBytes(@"C:\client.key"));//Generate a SIMPLEBLOB session key
byte[] session = GetRC4SessionBlobFromKey(keyMaterial, rsaClient);//Encrypt a key using public key and write it in a SIMPLEBLOB format
public byte[] GetRC4SessionBlobFromKey(byte[] keyData, RSACryptoServiceProvider publicKey)
{
using(MemoryStream ms = new MemoryStream())
using(BinaryWriter w = new BinaryWriter(ms))
{
w.Write((byte) 0x01); // SIMPLEBLOB
w.Write((byte) 0x02); // Version 2
w.Write((byte) 0x00); // Reserved
w.Write(0x00006801); // ALG_ID = RC4 for the encrypted key.
w.Write(0x0000a400); // CALG_RSA_KEYX
w.Write(publicKey.Encrypt(keyData, false));
w.Flush();
return ms.ToArray();
}
}
Why is that?