我有一个导出一组数据库行的程序。行内是需要加密的数据。我能够加密数据,但我似乎无法解密它。我按照Decrypt Xml file with asymetric key windows forms and windows service中显示的编码进行操作,我仍然收到消息“无法检索解密密钥”
目前,这是在同一用户的同一台机器上完成的,但情况并非总是如此。导出的文件将移动到另一台计算机,并在其他用户下导入。
这是我的加密例程......
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();
提前感谢您的帮助!!!
加里