Nuget首先需要添加引用:Portable.BouncyCastle
1 /// <summary> 2 /// PEM格式公钥转换成XML格式公钥 3 /// </summary> 4 /// <param name="publicKey">PEM格式公钥,(纯文字字符,注意不带-----BEGIN PUBLIC KEY-----和-----END PUBLIC KEY-----)</param> 5 /// <returns>转换后的XML格式公钥</returns> 6 public static string RSAPublicKeyXML(string publicKey) 7 { 8 RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey)); 9 10 return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>", 11 Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()), 12 Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned())); 13 }
1 /// <summary> 2 /// PEM格式私钥转换成XML格式私钥 3 /// </summary> 4 /// <param name="privateKey">PEM格式私钥,(纯文字字符,注意不带-----BEGIN PRIVATE KEY-----和-----END PRIVATE KEY-----)</param> 5 /// <returns></returns> 6 public static string RSAPrivateKeyToXml(string privateKey) 7 { 8 RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey)); 9 10 return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>", 11 Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()), 12 Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()), 13 Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()), 14 Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()), 15 Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()), 16 Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()), 17 Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()), 18 Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned())); 19 }