Using CngKey to generate an RSA key pair in PEM (DKIM compatible) using C # .... similar to "openssl rsa"

Is it possible to create an RSA key pair, export it to ASN1 format, compatible with DKIM PEM format, using only C #?

I would like to reduce my dependencies on third parties, but here are some of them that I found

Bouncy castle

Cryptography Application Block

Win32 PFXImportCertStore

Import PEM

Microsoft CLR Security Enhancements

Microsoft CNG

Here is the code for Microsoft CNG provider with .NET dll on codeplex (above) ... however, I don’t know how to export and import both public and private keys into DKIM compatible ASN1 format .

byte[] pkcs8PrivateKey = null; byte[] signedData = null; CngKey key = CngKey.Create(CngAlgorithm2.Rsa); byte[] exportedPrivateBytes = key.Export(CngKeyBlobFormat.GenericPrivateBlob); string exportedPrivateString= Encoding.UTF8.GetString(exportedPrivateBytes); pkcs8PrivateKey = Encoding.UTF8.GetBytes(exportedPrivateString); using (CngKey signingKey = CngKey.Import(pkcs8PrivateKey, CngKeyBlobFormat.Pkcs8PrivateBlob)) { using (RSACng rsa = new RSACng(signingKey)) { rsa.SignatureHashAlgorithm = CngAlgorithm.Sha1; signedData = rsa.SignData(dataToSign); } } 

Question

Are there any direct examples of using Microsoft libraries (Win32, PFX, or CLR on Codeplex) that illustrate how to create a key pair and export / import these values ​​in PEM format?

+4
source share
1 answer

So you just need the pkcs8 key.

 CngKeyCreationParameters ckcParams = new CngKeyCreationParameters() { ExportPolicy = CngExportPolicies.AllowExportPlainText, KeyCreationOptions = CngKeyCreationOptions.None, KeyUsage = CngKeyUsages.AllUsages, }; ckcParams.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.None)); myCngKey = CngKey.Create(CngAlgorithm.Rsa, null, ckcParams); byte[] privatePlainTextBlob = myCngKey.Export(CngKeyBlobFormat.Pkcs8PrivateBlob); Console.WriteLine(Convert.ToBase64String(privatePlainTextBlob)); } 

Your key pair is now contained in the PKCS # 8 ASN.1 encoded string.

0
source

All Articles