In: Computer Science
c#
Create a console application that protects an XML file, such as the following example. Note that the customer's credit card number and password are currently stored in clear text. The credit card must be encrypted so that it can be decrypted and used later, and the password must be salted and hashed:
<?xml version="1.0" encoding="utf-8"
?>
<customers>
<customer>
<name>Bob Smith</name>
<creditcard>1234-5678-9012-3456</creditcard>
<password>Pa$$w0rd</password>
</customer>
</customers>
using System;
using System.Xml;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
namespace CSCrypto
{
class Program
{
static void Main(string[] args)
{
Aes key = null;
try
{
key = Aes.Create();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
xmlDoc.Load("test.xml");
Encrypt(xmlDoc, "creditcard", key);
Console.WriteLine("The element was encrypted");
Console.WriteLine(xmlDoc.InnerXml);
Decrypt(xmlDoc, key);
Console.WriteLine("The element was decrypted");
Console.WriteLine(xmlDoc.InnerXml);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
if (key != null)
{
key.Clear();
}
}
}
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 specified 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 or not recommended for XML Encryption.");
}
edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod);
edElement.CipherData.CipherValue = encryptedElement;
EncryptedXml.ReplaceElement(elementToEncrypt, edElement,
false);
}
public static void Decrypt(XmlDocument Doc, SymmetricAlgorithm
Alg)
{
if (Doc == null)
throw new ArgumentNullException("Doc");
if (Alg == null)
throw new ArgumentNullException("Alg");
XmlElement encryptedElement =
Doc.GetElementsByTagName("EncryptedData")[0] as XmlElement;
if (encryptedElement == null)
{
throw new XmlException("The EncryptedData element was not
found.");
}
EncryptedData edElement = new EncryptedData();
edElement.LoadXml(encryptedElement);
EncryptedXml exml = new EncryptedXml();
byte[] rgbOutput = exml.DecryptData(edElement, Alg);
exml.ReplaceData(encryptedElement, rgbOutput);
}
}
}