C# 使用非对称密钥解密XML文件

C# 使用非对称密钥解密XML文件,c#,encryption,encryption-asymmetric,C#,Encryption,Encryption Asymmetric,我有一个导出一组数据库行的程序。行中包含需要加密的数据。我可以加密数据,但似乎无法解密。我按照中所示的编码,仍然收到消息“无法检索解密密钥” 目前,这是在同一台机器上、同一个用户下完成的,但情况并非总是如此。导出的文件将移动到另一台计算机,并在其他用户下导入 这是我的加密程序 XmlElement elementToEncrypt; var security = new CryptoKeySecurity(); // Give the creat

我有一个导出一组数据库行的程序。行中包含需要加密的数据。我可以加密数据,但似乎无法解密。我按照中所示的编码,仍然收到消息“无法检索解密密钥”

目前,这是在同一台机器上、同一个用户下完成的,但情况并非总是如此。导出的文件将移动到另一台计算机,并在其他用户下导入

这是我的加密程序

        XmlElement elementToEncrypt;

        var security = new CryptoKeySecurity();
        // Give the creating user full access 
        security.AddAccessRule(new CryptoKeyAccessRule(new NTAccount(Environment.UserDomainName, Environment.UserName), 
            CryptoKeyRights.FullControl, AccessControlType.Allow));

        // Specify that the key is to be stored in the machine key-store, and apply the security settings created above 
        var cspParams = new CspParameters
        {
            KeyContainerName = "XML_ENC_RSA_KEY",
            Flags = CspProviderFlags.UseMachineKeyStore,
            CryptoKeySecurity = security
        };
        var rsaKey = new RSACryptoServiceProvider(cspParams);

        elementToEncrypt = xmlDocument.GetElementsByTagName(elementName)[0] as XmlElement;

        var sessionKey = new RijndaelManaged() { KeySize = 256 };

        EncryptedXml eXml = new EncryptedXml();
        byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, sessionKey, false);

        var edElement = new EncryptedData()
        {
            Type = EncryptedXml.XmlEncElementUrl,
            Id = elementName,
            EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url)
        };

        var ek = new EncryptedKey();
        var encryptedKey = EncryptedXml.EncryptKey(sessionKey.Key, rsaKey, false);

        ek.CipherData = new CipherData(encryptedKey);
        ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);
        edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek));

        // Create a new KeyInfoName element. 
        var kin = new KeyInfoName() { Value = elementName };

        // Add the KeyInfoName element to the encryptedKey object. 
        ek.KeyInfo.AddClause(kin);
        edElement.CipherData.CipherValue = encryptedElement;
        EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false); 
这是我的解密程序

         var cspParams = new CspParameters
        {
            KeyContainerName = "XML_ENC_RSA_KEY",
            Flags = CspProviderFlags.UseMachineKeyStore | CspProviderFlags.UseExistingKey
        };
        var rsaKey = new RSACryptoServiceProvider(cspParams);

        var exml = new EncryptedXml(xmlDocument);
        exml.AddKeyNameMapping(elementName, rsaKey);
        exml.DecryptDocument(); 
提前感谢您的帮助

加里