How to change a key pair in xml format to PEM format in C #?

I am trying to change the generated xml key pair to PEM format. Here is my code.

CspParameters cspParams = new CspParameters(); cspParams.ProviderType = 1; cspParams.Flags = CspProviderFlags.UseArchivableKey; cspParams.KeyNumber = (int)KeyNumber.Exchange; rsaProvider = new RSACryptoServiceProvider(1024,cspParams); RSAParameters rsa_params = rsaProvider.ExportParameters(true); byte[] rsa_export = rsaProvider.ExportCspBlob(true); //here I've try to get private key data string data__ = Convert.ToBase64String(rsa_export); FileStream fs = new FileStream(privateKeyFileName, FileMode.CreateNew); string type = "RSA PRIVATE KEY"; string header = String.Format("-----BEGIN {0}-----\n", type); string footer = String.Format("\n-----END {0}-----", type); data__ = header+data__+footer; byte[] d_ = Encoding.Default.GetBytes(data__); //write to file fs.Write(d_, 0, d_.Length); fs.Close(); 

After I started it, I have a private key, but when I test with a key to create a certificate using the command:

 openssl req -new -x509 -key privatekey.pvk -config "C:\AppServ\php5\extras\openssl\openssl.cnf" -out myCert.cer -days 365 

An error has occurred

 unable to load Private Key 3004:error:0906D064:PEM routines:PEM_read_bio:bad base64 decode:.\crypto\pem\pem_lib.c:756: 
+4
source share
2 answers

Remember that openssl is picky about formatting a PEM certificate.

  • The file should contain: -----BEGIN CERTIFICATE----- on a separate line (i.e. it should be completed using a new line).
  • Each line of "gibberish" should have a width of 64 characters.
  • The file should end: -----END CERTIFICATE----- and also ends with a new line.
  • Do not save certificate text in Word. It must be in ASCII.
  • Do not mix DOS and UNIX line endings.

So, in your case, it looks like you are not wrapping the string "gibberish" by 64 characters, and your END tag skips a new line.

For others not creating their own key pairs, follow a few steps to normalize certificate files on Linux:

  • Run it through dos2unix: # dos2unix cert.pem
  • Run it with fold: # fold -w 64 cert.pem

If you are on Windows, try downloading Cygwin and you can get these conversion tools.

0
source

All Articles