日期:2014-05-18  浏览次数:21176 次

小妹请教RSA对XML加密部分机器报错疑问???
我对一个XML进行加密,加密后解密,在部分机器报如下错误:

请各位帮忙看看是哪里出问题!
2011/12/30 9:12:06: Exception Message:对象已存在。
 
 Source:mscorlib 
 StacTrace: 在 System.Security.Cryptography.CryptographicException.ThrowCryptogaphicException(Int32 hr)
  在 System.Security.Cryptography.Utils._CreateCSP(CspParameters param, Boolean randomKeyContainer, SafeProvHandle& hProv)
  在 System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
  在 System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle)
  在 System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair()
  在 System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters parameters, Boolean useDefaultKeySize)
  在 System.Security.Cryptography.RSACryptoServiceProvider..ctor(CspParameters parameters)

我加密方法如下:
C# code

        private XmlDocument EncryptXML(XmlDocument doc)
        {
            try
            {
                XmlElement xmlElemt;
                xmlElemt = doc.DocumentElement;

                CspParameters csp = new CspParameters();
                csp.KeyContainerName = "abcde123";
                csp.Flags = CspProviderFlags.UseMachineKeyStore;
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(csp);

                EncryptedXml xmlEnc = new EncryptedXml(doc);
                xmlEnc.AddKeyNameMapping("asyncKey", rsa);

                EncryptedData encXml = xmlEnc.Encrypt(xmlElemt, "asyncKey");

                EncryptedXml.ReplaceElement(xmlElemt, encXml, false);
                 
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return doc;
        }


解密方法如下:
C# code

        private XmlDocument DecryptXML(string filename)
        {
            XmlDocument doc = new XmlDocument();
            try
            {
                doc.Load(filename);//加载加密后的xml文件

                CspParameters csp = new CspParameters();
                csp.KeyContainerName = "abcde123";
                csp.Flags = CspProviderFlags.UseMachineKeyStore;
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(csp);

                EncryptedXml encXml = new EncryptedXml(doc);
                encXml.AddKeyNameMapping("asyncKey", rsa);
                encXml.DecryptDocument();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return doc;
        }



------解决方案--------------------
可能你的代码问题 或者 你已经创建了对象而后面还有创建对象代码 换个变量名试试
http://blog.csdn.net/llwinnner/article/details/4011936
http://www.csharpwin.com/csharpspace/8761r456.shtml