RSA2密钥转换《PEMToXML》
var rsaPrivate = PEMToXML_All(_Config.RSAPrivate);//私钥_Config.RSAPrivate
#region PEM转XML /// <summary> /// PEM格式的密钥转XML格式 /// </summary> /// <param name="pemkey">pem格式的密钥</param> /// <param name="isprikey">true:私钥;false:公钥</param> /// <returns>xml格式密钥</returns> public static string PEMToXML_All(string pemkey) { // 将PEM格式的密钥中的私钥标识替换为空 pemkey = pemkey.Replace("-----BEGIN PRIVATE KEY-----", "").Replace("-----END PRIVATE KEY-----", ""); // 声明变量 string rsaKey = string.Empty; object pemObject = null; RSAParameters rsaPara = new RSAParameters(); // 从字符串读取PEM格式的密钥 using (StringReader sReader = new StringReader(pemkey)) { var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(sReader); pemObject = pemReader.ReadObject(); } // 获取RSA私钥参数 RsaPrivateCrtKeyParameters key = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(pemkey)); rsaPara = new RSAParameters { Modulus = key.Modulus.ToByteArrayUnsigned(), Exponent = key.PublicExponent.ToByteArrayUnsigned(), D = key.Exponent.ToByteArrayUnsigned(), P = key.P.ToByteArrayUnsigned(), Q = key.Q.ToByteArrayUnsigned(), DP = key.DP.ToByteArrayUnsigned(), DQ = key.DQ.ToByteArrayUnsigned(), InverseQ = key.QInv.ToByteArrayUnsigned(), }; // 将RSA私钥参数导入到RSACryptoServiceProvider对象 RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(rsaPara); // 将RSACryptoServiceProvider对象转换为XML格式的字符串 using (StringWriter sw = new StringWriter()) { sw.Write(rsa.ToXmlString(true)); rsaKey = sw.ToString(); } return rsaKey; } #endregion