C#.NET FRAMEWORK XML私钥转PKCS1,PKCS8
使用了 BouncyCastle 这个dll ,到nuget中下载即可。
XML私钥转PKCS1
public string XmlToPem(string xmlPrivateKey)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPrivateKey);
string priKey = null;
var p = rsa.ExportParameters(true);
var key = new RsaPrivateCrtKeyParameters(
new BigInteger(1, p.Modulus), new BigInteger(1, p.Exponent), new BigInteger(1, p.D),
new BigInteger(1, p.P), new BigInteger(1, p.Q), new BigInteger(1, p.DP), new BigInteger(1, p.DQ),
new BigInteger(1, p.InverseQ));
using (TextWriter sw = new StringWriter())
{
var pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(sw);
pemWriter.WriteObject(key);
pemWriter.Writer.Flush();
priKey = sw.ToString();
}
return priKey;
}
XML私钥转PKCS8
public static string XmlToPKCS8(string xmlPrivateKey)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPrivateKey);
string priKey = null;
var bcKeyPair = DotNetUtilities.GetRsaKeyPair(rsa);
var pkcs8Gen = new Pkcs8Generator(bcKeyPair.Private);
var pemObj = pkcs8Gen.Generate();
var pkcs8Out = new StringWriter();
var pemWriter = new PemWriter(pkcs8Out);
pemWriter.WriteObject(pemObj);
priKey = pkcs8Out.ToString();
pkcs8Out.Close();
return priKey;
}