Skip to content

Instantly share code, notes, and snippets.

@ssukhpinder
Created September 21, 2020 05:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssukhpinder/b8deaae432ab768daaf3341e3cdd4a75 to your computer and use it in GitHub Desktop.
Save ssukhpinder/b8deaae432ab768daaf3341e3cdd4a75 to your computer and use it in GitHub Desktop.
public static void Encrypt(XmlDocument Doc, string ElementName, SymmetricAlgorithm Key)
{
if (Doc == null)
throw new ArgumentNullException("Doc");
if (ElementName == null)
throw new ArgumentNullException("ElementToEncrypt");
if (Key == null)
throw new ArgumentNullException("Alg");
XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementName)[0] as XmlElement;
if (elementToEncrypt == null)
{
throw new XmlException("The XML element was not found");
}
EncryptedXml eXml = new EncryptedXml();
byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, Key, false);
EncryptedData edElement = new EncryptedData();
edElement.Type = EncryptedXml.XmlEncElementUrl;
string encryptionMethod = null;
if (Key is Aes)
{
encryptionMethod = EncryptedXml.XmlEncAES256Url;
}
else
{
throw new CryptographicException("The specified algorithm is not supported.");
}
edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod);
edElement.CipherData.CipherValue = encryptedElement;
EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment