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

浪子不回头ぞ 提交于 2019-12-10 09:04:35

问题


I've try to change created key pair in xml format 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've run it I've got a private key but when I test by using the key to create a certificate using command:

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

an error occured

unable to load Private Key
3004:error:0906D064:PEM routines:PEM_read_bio:bad base64 decode:.\crypto\pem\pem_lib.c:756:

回答1:


Take a look at this blog post: http://pstaev.blogspot.com.es/2010/08/convert-rsa-public-key-from-xml-to-pem.html




回答2:


Remember that openssl is picky about PEM certificate formatting.

  1. The file must contain: -----BEGIN CERTIFICATE----- on a separate line (i.e. it must be terminated with a newline).
  2. Each line of "gibberish" must be 64 characters wide.
  3. The file must end with: -----END CERTIFICATE----- and also be terminated with a newline.
  4. Don't save the cert text with Word. It must be in ASCII.
  5. Don't mix DOS and UNIX style line terminations.

So in your case, it appears you are not line wrapping the "gibberish" at 64 characters, and your END tag is missing the newline.

For others out there not writing their own key pairs, here are a few steps you can take to normalize your certificate files on Linux:

  1. Run it through dos2unix: # dos2unix cert.pem
  2. Run it through fold: # fold -w 64 cert.pem

If you're on Windows, try downloading Cygwin, and you should be able to get these conversion tools.



来源:https://stackoverflow.com/questions/6995458/how-can-i-change-key-pair-in-xml-format-to-pem-format-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!