Encrypt an XML document using an asymmetric key : RSA « Security « C# / CSharp Tutorial






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.Load("test.xml");
        RSA rsaKey = new RSACryptoServiceProvider();
        Encrypt(xmlDoc, "creditcard", rsaKey, "rsaKey");
        Console.WriteLine(xmlDoc.OuterXml);
        xmlDoc.Save("test.xml");

        Decrypt(xmlDoc, rsaKey, "rsaKey");
        xmlDoc.Save("test.xml");
        Console.WriteLine(xmlDoc.OuterXml);
        rsaKey.Clear();
    }

    public static void Encrypt(XmlDocument Doc, string ElementToEncrypt, 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.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);
        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();

    }

}








35.10.RSA
35.10.1.Asymmetric cryptography
35.10.2.Encrypt with RSACryptoServiceProvider
35.10.3.Using RSACryptoServiceProvider
35.10.4.Using RSAPKCS1SignatureDeformatter
35.10.5.RSACryptoServiceProvider reads from xml key
35.10.6.CspParameters and RSACryptoServiceProvider
35.10.7.Encrypt an XML document using an asymmetric key
35.10.8.Use RSAPKCS1SignatureFormatter to create a digital signature and then uses the RSAPKCS1SignatureDeformatter class to verify the signature.