This will not work with CNG(KSP)
Steps 1
1. When we create key/pair, store the KeyContainerName.
2. Sign CSR with created keys and get the certificate(one of CER/DER/PEM/CRT) format.
3. Open the certificate using x509certificate2 class, create CspParameter class. Assign the KeyContainerName to CspParamater class.
4. Create RsaCryptoProvider class using CspParamater, and assign it to PrivateKey of x509certificate2.
5. Using Export(pfx, password) option.
6. Clear RsaCryptoProvider using PersistCsp = false, and Clear().
Note
1. If you don't pass valid KeyContainerName, default will be created. But assigning to PrivateKey property will throw exception about Key mismatch(after all they are strongly related).
2. Clear the KeyContainer for better security purposes.
Sample code to get u started.
CspParameters p = new CspParameters();
p.ProviderName = "Microsoft Enhanced Cryptographic Provider v1.0";
p.ProviderType = 1;
p.KeyContainerName = "your container name";
p.KeyNumber = (int)AT_KEYEXCHANGE;
RSACryptoServiceProvider csp = new RSACryptoServiceProvider(p);
X509Certificate2 cer = new X509Certificate2("sss.cer");
cer.PrivateKey = csp;
byte[] bytes = cer.Export(X509ContentType.Pfx, "12345");
FileStream stream = new FileStream("CASigned.pfx", FileMode.CreateNew);
stream.Write(bytes, 0, bytes.Length);
stream.Close();
X509Certificate2 c1 = new X509Certificate2("CASigned.pfx", "12345");
bool value = c1.HasPrivateKey;
No comments:
Post a Comment