/// <summary> /// 获取RSA的 私有、公有的秘钥 /// </summary> /// <param name="savePath">秘钥保存路径</param> /// <param name="keyName">密钥的名字</param> /// <returns></returns> public static bool CreateRSAKey(string savePath, string keyName) { try { if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { RSAParameters publicParam = rsa.ExportParameters(false); XmlSerializer privateXml = new XmlSerializer(publicParam.GetType()); string pathPublic = savePath.TrimEnd('/', '\\') + "/" + keyName + "_rsa.pub"; using (FileStream fs = new FileStream(pathPublic, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { privateXml.Serialize(fs, publicParam); } RSAParameters privateParam = rsa.ExportParameters(true); XmlSerializer publicXml = new XmlSerializer(privateParam.GetType()); string pathPrivate = savePath.TrimEnd('/', '\\') + "/" + keyName + "_rsa"; using (FileStream fs = new FileStream(pathPrivate, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { publicXml.Serialize(fs, privateParam); } } return(true); } catch (System.Exception error) { System.Console.WriteLine("CreateRSAPublicKey Error: " + error.Message); return(false); } }
/// <summary> /// Private method for serializing RSAParameters to XML-string /// </summary> private string RSAParametersToXML(RSAParameters key) { XmlSerializer serializer = new XmlSerializer(key.GetType()); using (StringWriter textWriter = new StringWriter()) { serializer.Serialize(textWriter, key); return(textWriter.ToString()); } }
public static string ToXmlString(this RSAParameters rsaParameters) { var xmlSerializer = new XmlSerializer(rsaParameters.GetType()); using (var textWriter = new StringWriter()) { xmlSerializer.Serialize(textWriter, rsaParameters); return(textWriter.ToString()); } }
// not always implemented in https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.rsa public static void FromXmlString(RSA rsa, string xmlString) { var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xmlString); var nodes = xmlDoc.DocumentElement.ChildNodes.Cast <XmlNode>() .ToDictionary(n => n.Name, n => Convert.FromBase64String(n.InnerText.Trim())); object parameters = new RSAParameters(); //boxing needed to set values foreach (var node in nodes) { parameters.GetType().GetField(node.Key).SetValue(parameters, node.Value); } rsa.ImportParameters((RSAParameters)parameters); }