如何在C#中将xml格式的密钥对更改为PEM格式? [英] How can I change key pair in xml format to PEM format in C#?

查看:97
本文介绍了如何在C#中将xml格式的密钥对更改为PEM格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将xml格式的创建的密钥对更改为PEM格式。
这是我的代码。

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

发生错误

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


推荐答案

请记住,openssl对PEM证书格式有些挑剔。

Remember that openssl is picky about PEM certificate formatting.


  1. 文件必须包含:
    ----- BEGIN证书-----
    在单独的行上(即,必须以换行符终止)。

  2. 乱码的每一行必须为64个字符宽。

  3. 文件的结尾必须为:
    ---- -END CERTIFICATE -----
    ,并以newlin终止e。

  4. 不要用Word保存证书文本。

  5. 请勿混合使用DOS和UNIX样式的行终止符。

  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.

因此,在您的情况下,看来您不是用64个字符换行了乱码,而END标记缺少换行符。

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

对于其他人则没有编写自己的密钥对,您可以按照以下步骤对Linux上的证书文件进行规范化:

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. 通过dos2unix运行它:#dos2unix cert.pem

  2. 通过折叠运行:#折叠-w 64 cert.pem

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

如果您使用的是Windows,请尝试下载 Cygwin ,您应该就能获得这些转换工具。

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

这篇关于如何在C#中将xml格式的密钥对更改为PEM格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆