我为加密/解密流编写了一个代码块。该代码在我的本地机器上运行。但是当我在网络上发布我的代码时,解密函数抛出“坏数据”异常这是我的加密和解密函数
private static MemoryStream EncryptStream(XmlDocument xmlDoc, XmlElement elementToEncrypt, string password)
{
CspParameters cspParams = new CspParameters();
cspParams.KeyContainerName = password;
RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);
RijndaelManaged sessionKey = null;
try
{
if (xmlDoc == null)
throw new ArgumentNullException("xmlDoc");
if (rsaKey == null)
throw new ArgumentNullException("rsaKey");
if (elementToEncrypt == null)
throw new ArgumentNullException("elementToEncrypt");
sessionKey = new RijndaelManaged();
sessionKey.KeySize = 256;
EncryptedXml eXml = new EncryptedXml();
byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, sessionKey, false);
EncryptedData edElement = new EncryptedData();
edElement.Type = EncryptedXml.XmlEncElementUrl;
edElement.Id = EncryptionElementID;
edElement.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);
EncryptedKey ek = new EncryptedKey();
byte[] encryptedKey = EncryptedXml.EncryptKey(sessionKey.Key, rsaKey, false);
ek.CipherData = new CipherData(encryptedKey);
ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);
edElement.KeyInfo = new KeyInfo();
KeyInfoName kin = new KeyInfoName();
kin.Value = KeyName;
ek.KeyInfo.AddClause(kin);
edElement.CipherData.CipherValue = encryptedElement;
edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek));
EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
if (sessionKey != null)
{
sessionKey.Clear();
}
rsaKey.Clear();
MemoryStream stream = new MemoryStream();
xmlDoc.Save(stream);
stream.Position = 0;
Encoding encodeing = System.Text.UnicodeEncoding.Default;
return stream;
}
catch (Exception e)
{
if (sessionKey != null)
{
sessionKey.Clear();
}
rsaKey.Clear();
throw (e);
}
}
private static MemoryStream DecryptStream(XmlDocument xmlDoc, string password)
{
CspParameters cspParams = new CspParameters();
cspParams.KeyContainerName = password;
RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);
EncryptedXml exml = null;
try
{
if (xmlDoc == null)
throw new ArgumentNullException("xmlDoc");
if (rsaKey == null)
throw new ArgumentNullException("rsaKey");
exml = new EncryptedXml(xmlDoc);
exml.AddKeyNameMapping(KeyName, rsaKey);
exml.DecryptDocument();
rsaKey.Clear();
MemoryStream outStream = new MemoryStream();
xmlDoc.Save(outStream);
outStream.Position = 0;
return outStream;
}
catch (Exception e)
{
rsaKey.Clear();
throw (e);
}
}
在“exml.DecryptDocument();”上抛出异常 线。
您对问题和解决方案有任何想法吗?
编辑:
在MSDN页面中,有如下备注
要将 XML 加密与 X.509 证书一起使用,您必须安装 Microsoft 增强加密提供程序,并且 X.509 证书必须使用增强提供程序。如果您没有安装 Microsoft 增强加密提供程序或 X.509 证书不使用增强提供程序,则在解密 XML 文档时将引发带有“未知错误”的 CryptographicException。
您对“Microsoft Enhanced Cryptographic Provider”和“X.509 证书”有任何想法吗?我的问题与这些有关吗?