Skip to main content
 首页 » 编程设计

c#之如何在一个程序中用 RSA 加密 Xml 文件并在另一个程序中解密

2024年02月13日11zhwl

我需要加密/解密整个 XML 文件。我像在 this MSDN post 中一样使用 RSA但问题是我必须在一个程序(Windows 窗体程序)中加密并在 Windows 服务中解密。 Windows 服务如何知道我生成的 RSA key 以便解密?

加解密代码为:

 public class EncryptDecrpt 
    { 
        public static void Encrypt(XmlDocument doc, string ElementToEncrypt, string EncryptionElementID, RSA Alg, 
            string KeyName) 
        { 
            try 
            { 
                //Check the arguments 
                if (doc == null) 
                    throw new ArgumentNullException("doc"); 
                if (ElementToEncrypt == null) 
                    throw new ArgumentNullException("ElementToEncrypt"); 
                if (EncryptionElementID == null) 
                    throw new ArgumentNullException("EncryptionElementID"); 
                if (Alg == null) 
                    throw new ArgumentNullException("Alg"); 
                if (KeyName == null) 
                    throw new ArgumentNullException("KeyName"); 
 
 
                // Find the specified element in the XmlDocument object 
                // and create a new XmlElement object 
                XmlElement elementToEncrypt = doc.GetElementsByTagName(ElementToEncrypt)[0] as XmlElement; 
                if (elementToEncrypt == null) 
                    throw new XmlException("The specified element was not found"); 
 
                RijndaelManaged sessionKey = null; 
 
                // Create a 256 bit Rijandel key 
                sessionKey = new RijndaelManaged(); 
                sessionKey.KeySize = 256; 
 
                EncryptedXml eXml = new EncryptedXml(); 
 
                byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, sessionKey, false); 
 
                // Construct an EncryptedData object and populate 
                // it with the desired encryption information 
 
                EncryptedData edElement = new EncryptedData(); 
                edElement.Type = EncryptedXml.XmlEncElementUrl; 
                edElement.Id = EncryptionElementID; 
 
                edElement.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url); 
                // Encrypt the session key and add it to an EncryptedKey element 
                EncryptedKey ek = new EncryptedKey(); 
 
                byte[] encryptedKey = EncryptedXml.EncryptKey(sessionKey.Key, Alg, false); 
 
                ek.CipherData = new CipherData(encryptedKey); 
 
                ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); 
 
                DataReference dRef = new DataReference(); 
 
                // Specify the EncryptedData URI 
                dRef.Uri = "#" + EncryptionElementID; 
 
                ek.AddReference(dRef); 
 
                edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek)); 
 
                KeyInfoName kin = new KeyInfoName(); 
 
                kin.Value = KeyName; 
 
                ek.KeyInfo.AddClause(kin); 
 
                edElement.CipherData.CipherValue = encryptedElement; 
 
                // Replace the element from the original XmlDocument 
                // object with the EncrytedData element 
                EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false); 
            } 
            catch (Exception e) 
            { 
                // rethrow the exception 
                throw e; 
            } 
 
        } 
 
        public static void Decrypt(XmlDocument Doc, RSA Alg, string KeyName) 
        { 
            // Check the arguments.    
            if (Doc == null) 
                throw new ArgumentNullException("Doc"); 
            if (Alg == null) 
                throw new ArgumentNullException("Alg"); 
            if (KeyName == null) 
                throw new ArgumentNullException("KeyName"); 
 
            // Create a new EncryptedXml object. 
            EncryptedXml exml = new EncryptedXml(Doc); 
 
            // Add a key-name mapping.  
            // This method can only decrypt documents  
            // that present the specified key name. 
            exml.AddKeyNameMapping(KeyName, Alg); 
 
            // Decrypt the element. 
            exml.DecryptDocument(); 
 
        } 
 
    } 

Windows Form程序中的代码是:

 private void SaveForm() 
        { 
            try 
            { 
                string fileName = System.IO.Path.Combine(Application.StartupPath, "alphaService.xml"); 
                XDocument doc = new XDocument(); 
                XElement xml = new XElement("Info", 
                    new XElement("DatabaseServerName", txtServerName.Text), 
                    new XElement("DatabaseUserName", txtDatabaseUserName.Text), 
                    new XElement("DatabasePassword", txtDatabasePassword.Text), 
                    new XElement("ServiceAccount", txtAccount.Text), 
                    new XElement("ServicePassword", txtServicePassword.Text), 
                    new XElement("RegistrationCode", txtRegistrationCode.Text)); 
 
                doc.Add(xml); 
                doc.Save(fileName); 
 
                // Encrypt 
                XmlDocument xmlDoc = new XmlDocument(); 
                xmlDoc.Load(fileName); 
                // Create a new CspParameters object to specify 
                // a key container 
                CspParameters cspParams = new CspParameters(); 
                cspParams.KeyContainerName = "XML_ENC_RSA_KEY"; 
 
                RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams); 
 
                EncryptDecrpt.Encrypt(xmlDoc, "info", "EncryptedElement1", rsaKey, "rsaKey"); 
 
                xmlDoc.Save(fileName); 
 
                MessageBox.Show(xmlDoc.OuterXml); 
 
                EncryptDecrpt.Decrypt(xmlDoc, rsaKey, "rsaKey"); 

Windows 服务如何知道 RSA key 或我如何才能做到这一点?

请您参考如下方法:

PKI 和 key 管理本身就是一本书。但这归结为:您在执行解密的服务器上创建了一个 key 对。解密需要私钥,您不想移动私钥(备份目的除外)。你应该只做一次,比如说,5 年。

然后您将公钥安全地分发给客户端。您可以通过将 key 合并到您的代码中来做到这一点——只要您可以信任公钥。然后使用公钥执行加密。同样,分配通常对每个 key 对执行一次。