using System;
using System.Xml;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
class Program
{
static void Main(string[] args)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
xmlDoc.Load("test.xml");
RSA rsaKey = new RSACryptoServiceProvider();
// Encrypt the "creditcard" element.
Encrypt(xmlDoc, "creditcard", "EncryptedElement1", rsaKey, "rsaKey");
// Encrypt the "creditcard2" element.
Encrypt(xmlDoc, "creditcard2", "EncryptedElement2", rsaKey, "rsaKey");
Console.WriteLine("Encrypted XML:");
Console.WriteLine(xmlDoc.OuterXml);
// Decrypt the "creditcard" element.
Decrypt(xmlDoc, rsaKey, "rsaKey");
Console.WriteLine("Decrypted XML:");
Console.WriteLine(xmlDoc.OuterXml);
rsaKey.Clear();
}
public static void Encrypt(XmlDocument Doc, string ElementToEncrypt, string EncryptionElementID, RSA Alg, string KeyName)
{
XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementToEncrypt)[0] as XmlElement;
RijndaelManaged 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, Alg, 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);
DataReference dRef = new DataReference();
dRef.Uri = "#" + EncryptionElementID;
ek.AddReference(dRef);
edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek));
edElement.CipherData.CipherValue = encryptedElement;
EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
}
public static void Decrypt(XmlDocument Doc, RSA Alg, string KeyName)
{
EncryptedXml exml = new EncryptedXml(Doc);
exml.AddKeyNameMapping(KeyName, Alg);
exml.DecryptDocument();
}
}
// <root>
// <creditcard xmlns="myNamespace" Id="tag1">
// <number>A</number>
// <expiry>02/02/2011</expiry>
// </creditcard>
// <creditcard2 xmlns="myNamespace" Id="tag2">
// <number>2</number>
// <expiry>02/02/2012</expiry>
// </creditcard2>
// </root>