转自: https://www.jianshu.com/p/f22b4e565ec1
从原来framework下的代码搬过来,结果不能用。原来的代码
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); byte[] cipherbytes; rsa.FromXmlString(privatekey); cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false); return Encoding.UTF8.GetString(cipherbytes);
报错 FromXmlString 这个方法在环境下不可用。
百度看到开头链接文章,扩展两个方法 ,当然只用到 fromxmlstring
public static void FromXmlString(this RSA rsa, string xmlString) { RSAParameters parameters = new RSAParameters(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xmlString); if (xmlDoc.DocumentElement.Name.Equals("RSAKeyValue")) { foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes) { switch (node.Name) { case "Modulus": parameters.Modulus = Convert.FromBase64String(node.InnerText); break; case "Exponent": parameters.Exponent = Convert.FromBase64String(node.InnerText); break; case "P": parameters.P = Convert.FromBase64String(node.InnerText); break; case "Q": parameters.Q = Convert.FromBase64String(node.InnerText); break; case "DP": parameters.DP = Convert.FromBase64String(node.InnerText); break; case "DQ": parameters.DQ = Convert.FromBase64String(node.InnerText); break; case "InverseQ": parameters.InverseQ = Convert.FromBase64String(node.InnerText); break; case "D": parameters.D = Convert.FromBase64String(node.InnerText); break; } } } else { throw new Exception("Invalid XML RSA key."); } rsa.ImportParameters(parameters); } public static string ToXmlString(this RSA rsa, bool includePrivateParameters) { RSAParameters parameters = rsa.ExportParameters(includePrivateParameters); if (includePrivateParameters) { 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>", Convert.ToBase64String(parameters.Modulus), Convert.ToBase64String(parameters.Exponent), Convert.ToBase64String(parameters.P), Convert.ToBase64String(parameters.Q), Convert.ToBase64String(parameters.DP), Convert.ToBase64String(parameters.DQ), Convert.ToBase64String(parameters.InverseQ), Convert.ToBase64String(parameters.D)); } return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>", Convert.ToBase64String(parameters.Modulus), Convert.ToBase64String(parameters.Exponent)); }
然后
var privateKeyRsaProvider = RSA.Create(); privateKeyRsaProvider.FromXmlStringEx(privatekey); var r= Encoding.UTF8.GetString(privateKeyRsaProvider.Decrypt(Convert.FromBase64String(content), RSAEncryptionPadding.Pkcs1)); return r;
搞定。
原文:https://www.cnblogs.com/jzz228/p/11337884.html