.NET Cryptography

61
1 .NET Cryptography Object Oriented Programming III

description

.NET Cryptography. Object Oriented Programming III. XML Encryption. Notes from : http://www-106.ibm.com/developerworks/library/x-encrypt/index.html by Bilal Siddiqui “Secure XML” by Eastlake and Niles Addison Wesley “.NET Security and Cryptography” by Thorsteinson and Ganesh. - PowerPoint PPT Presentation

Transcript of .NET Cryptography

1

.NET Cryptography

Object Oriented Programming III

2

XML Encryption

Notes from :

http://www-106.ibm.com/developerworks/library/x-encrypt/index.html by Bilal Siddiqui

“Secure XML” by Eastlake and Niles Addison Wesley

“.NET Security and Cryptography” by Thorsteinson and Ganesh

3

Not a replacement for SSL

• XML Encryption adds

Encrypting part of the data being exchanged

Secure sessions between more than two parties

4

General Form 1

<EncryptedData>

<CipherData>

<CipherValue>

Cipher Text Gibberish in Base 64

</CipherValue>

</CipherData>

</EncryptedData>

5

General Form 2

<EncryptedData>

<CipherData>

<CipherReference>

pointer (URL) to gibberish

</CipherReference>

</CipherData>

</EncryptedData>

6

• Replaces the encrypted element or

• Serves as the new document root

• May contain a KeyInfo element that describes the key needed for decryption (borrowed from XML Digital Signature)

EncryptedData is the core element

7

General Example (1)

<MedInfo> <ID> <Name> <Address> </ID> <Medical>…</Medical> <Financial>…</Financial></MedInfo>

8

General Example (2)

<MedInfo> <ID>….</ID> <EncryptedData> <KeyInfo> <KeyName>Medical </KeyInfo> <CipherData> <CipherValue> gibberish </EncryptedData>

9

General Example (3)

<Financial> <EncryptedData> <KeyInfo> <KeyName>Pay </KeyInfo> <CipherData> <CipherValue> gibberish

</EncryptedData></Finacial>

</MedInfo>

10

Detailed Example (Listing 1)

<purchaseOrder>

<Order>

<Item>book</Item>

<Id>123-958-74598</Id>

<Quantity>12</Quantity>

</Order>

<Payment>

<CardId>123654-8988889-9996874</CardId>

<CardName>visa</CardName>

<ValidDate>12-10-2004</ValidDate>

</Payment>

</purchaseOrder>

11

Encrypting the Entire File (Listing 2)

<?xml version='1.0' ?>

<EncryptedData xmlns='http://www.w3.org/2001/04/xmlenc#' Type='http://www.isi.edu/in-notes/iana/assignments/media-types/text/xml'>

<CipherData>

<CipherValue>A23B45C56</CipherValue>

</CipherData>

</EncryptedData>

IANA = Internet Assigned Numbers Authority a function of The Internet Corporationfor Assigned Names and Numbers

12

Encrypting The Payment (Listing 3)

<?xml version='1.0' ?> <PurchaseOrder> <Order> <Item>book</Item> <Id>123-958-74598</Id> <Quantity>12</Quantity> </Order> <EncryptedData Type='http://www.w3.org/2001/04/xmlenc#Element' xmlns='http://www.w3.org/2001/04/xmlenc#'> <CipherData> <CipherValue>A23B45C564587</CipherValue> </CipherData> </EncryptedData> </PurchaseOrder>

One element

13

Encrypting Only the CardId (Listing 4)

<?xml version='1.0' ?> <PurchaseOrder> <Order> <Item>book</Item> <Id>123-958-74598</Id> <Quantity>12</Quantity> </Order> <Payment> <CardId> <EncryptedData Type='http://www.w3.org/2001/04/xmlenc#Content' xmlns='http://www.w3.org/2001/04/xmlenc#'> <CipherData> <CipherValue>A23B45C564587</CipherValue> </CipherData> </EncryptedData> </CardId> <CardName>visa</CardName> <ValidDate>12-10-2004</CardName> </Payment> </PurchaseOrder>

14

Encrypting Non-XML Data(Listing 5)

<?xml version='1.0' ?>

<EncryptedData xmlns='http://www.w3.org/2001/04/xmlen#'

Type='http://www.isi.edu/in-notes/iana/assignments/media-types/jpeg' >

<CipherData>

<CipherValue>A23B45C56</CipherValue>

</CipherData>

</EncryptedData>

15

Sending a Public key(listing 6)<?xml version='1.0' ?> <SecureCommunicationDemonstration> <EncryptedKey CarriedKeyName="Muhammad Imran" xmlns='http://www.w3.org/2001/04/xmlenc#'> <ds:KeyInfo xmlns:ds='http://www.w3.org/2000/09/xmldsig#'> <ds:KeyValue>1asd25fsdf2dfdsfsdfds2f1sd23 </ds:KeyValue> </ds:KeyInfo> </EncryptedKey></SecureCommunicationDemonstration>

16

Receiving a Session key encrypted to the public key (listing 7)

<?xml version='1.0' ?> <SecureCommunicationDemonstration> <EncryptedKey CarriedKeyName="Imran Ali" xmlns='http://www.w3.org/2001/04/xmlenc#'> <EncryptionMethod Algorithm= "http://www.w3.org/2001/04/xmlenc#rsa-1_5"/> <CipherData> <CipherValue>xyza21212sdfdsfs7989fsdbc </CipherValue> </CipherData> </EncryptedKey></SecureCommunicationDemonstration>

17

Data Encrypted to Secret Key (Listing 8)

<?xml version='1.0' ?> <<SecureCommunicationDemonstration> <Order> <Item>book</Item> <Id>123-958-74598</Id> <Quantity>12</Quantity> <CardName>Visa</CardName> <ExpDate>10-10-2005</ExpDate> <EncryptedData Type='http://www.w3.org/2001/04/xmlenc#Element' xmlns='http://www.w3.org/2001/04/xmlenc#'> <EncryptionMethod Algorithm='http://www.w3.org/2001/04/xmlenc#tripledes-cbc '/> <ds:KeyInfo xmlns:ds='http://www.w3.org/2000/09/xmldsig#'> <ds:KeyName>Imran ali</ds:KeyName> </ds:KeyInfo> <CipherData> <CipherValue>A23B45C564587</CipherValue> </CipherData> </EncryptedData> </Order> </SecureCommunicationDemonstration>

18

Pointing to encrypted data (listing 9)

<?xml version='1.0' ?> <EncryptedData xmlns='http://www.w3.org/2001/04/xmlenc#' Type= 'http://www.w3.org/2001/04/xmlenc#Element'> <ds:KeyInfo xmlns:ds='http://www.w3.org/2000/09/xmldsig#'> <ds:KeyName>Imran ali</ds:KeyName </ds:KeyInfo> <CipherData> <CipherReference URI="www.waxsys.com/secureData/waxFile.txt"/> </CipherData> </EncryptedData>

19

Point to a distant encrypted element (Listing 10)

<?xml version='1.0' ?> <EncryptedData ID="Enc-Data" xmlns='http://www.w3.org/2001/04/xmlenc#'

Type='http://www.w3.org/2001/04/xmlenc#Element' > <CipherReference URI="http://www.waxsys.com/EncFile.xml" > <Transforms xmlns:ds="http://www.w3.org/2000/09/xmldsig#" > <ds:Transform Algorithm="http://www.w3.org/TR/1999/REC- xpath-19991116"> <wax:XPath xmlns:wax="http://www.waxsys.com/xpathNS"> PruchaseOrder/EncryptedData [@Id="Imran-Enc-Data"] </wax:XPath> </ds:Transform> </Transforms> </CipherReference> </EncryptedData>

20

Hybrid Encryption

• The way it’s done today

• Bulk encryption using symmetric (session) keys – fast

• Symmetric key exchange problem solved by encrypting the session key with the receivers public key

21

.Net Crypto API Example

• The receiver builds an RSA key pair• The public key of the receiver is used by the

sender to encrypt a symmetric session key• The encrypted session key along with the

encrypted elements are sent to the receiver• The receiver decrypts the session key using her

private RSA key• She then decrypts the encrypted element using

the symmetric session key

22

The RSA Public key in XML

<RSAKeyValue><Modulus>z9zv0HMRK44BrjYIQtmKlDkA6WnQCIVOYmOj

y/eKhFqXJM024JybC/5hOCQoYRRo5iYRopIV4gBZUBSolxgk8jIr38iO84lDoSisPl3ikcob/aCuhPe8jSl4zbKpiJ+rqQE8rSNJ3XDPDVIiRoDbSRbn04x210tjYNMbePw0RQk=</Modulus>

<Exponent>AQAB</Exponent></RSAKeyValue>

23

The RSA Public/Private Key Pair

<RSAKeyValue>

<Modulus>

z9zv0HMRK44BrjYIQtmKlDkA6WnQCIVOYmOjy/eKhFqXJM024JybC/5hOCQoYRRo5iYRopIV4gBZUBSolxgk8jIr38iO84lDoSisPl3ikcob/aCuhPe8jSl4zbKpiJ+rqQE8rSNJ3XDPDVIiRoDbSRbn04x210tjYNMbePw0RQk=

</Modulus><Exponent>AQAB</Exponent>

24

<P>54xO9DFJ4Mydzqrq8/0mcWInv4pU+bJHx1W1TYiybkRs7TchIq56z1JSgedhSxYvGHfHKzDcdplK2PHC9Aik2w==</P>

<Q>5dBTIHj9btkq9Nss0ZC04OyRGjssKJs8+Y89MOhs9BB1YNnk6Ci6PqV8F2P8FwcSFLXb5+II7nuvRTGS5enQ6w==</Q>

<D>sLBBOZNWGQvQ6eEMDKcWYQBDgiVrrJKEGqZP6WU13WOT7rhx2WPFd+B3i11Q5ZSPxnK9ss8ywrVBNg0ZcbYYUC+g6fYsfylKv1Lbpxr9h002syvRjmyywRcD9+TfvrVhOe27QYJKlE/QX4SHSgnTxq4qkmHdTxZRtoRGGLdZ8XE=</D></RSAKeyValue>

25

The Session Key

<EncryptedKey CarriedKeyName="My 3DES Session Key">

<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/>

<ds:KeyInfo>

<KeyName>My Private Key</KeyName>

</ds:KeyInfo>

26

<CipherData> <CipherValue> Shy7Nzo/ctBPAhwubFiAYpNNB2CuM4TpCUozP2oQZrEMT03O EzspgkBaItai8ImBUiSUT1KlPCbawG2edz40ISgJ+G+Sl4m6ZNm L0//gqs4/7eUyLY0rSFeCnW9hKU/hr0r4wDJaKiI+hS68OTHeBBc GLCyFEPSCQXeqbnvqQBo= </CipherValue></CipherData></EncryptedKey>

27

The Original Invoice

<invoice><items> <item>

<desc>Deluxe corncob pipe</desc> <unitprice>14.95</unitprice> <quantity>1</quantity> </item> </items>

28

<creditinfo> <cardnumber>0123456789</cardnumber> <expiration>01/06/2005</expiration> <lastname>Finn</lastname> <firstname>Huckleberry</firstname></creditinfo>

</invoice>

29

The Encrypted Invoice

<invoice><items><item>

<desc>Deluxe corncob pipe</desc><unitprice>14.95</unitprice><quantity>1</quantity></item></items>

30

<EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element">

<ds:KeyInfo><KeyName>My 3DES Session Key</KeyName></ds:KeyInfo>

<CipherData>

<CipherValue>ZS0og/w6JtPj0BDtU4XiAS3ybUsqh4tvp4ItoNO8ZzWUSVl8290HHVG2MfbjPSr00dCftHpaBd8GBgHOUSqG6wiia3EYy8Bgz7y6NeQ6zFu9i3J34Fy+uWETjmkROE/mg+RU0IxQTkcDWQVfUq6TECNafP9voSvbOGTNbt87Rb0BDcjbAWWLjKkOT6KOOVwfq60TJxmmkxFonqwVAY2ARlm/yBqvbo2BHux5fvZFZBF5jCPZPkuOClYZVXpY3wVB</CipherValue></CipherData></EncryptedData></invoice>

31

The C# Code (from Thorsteinson and Ganesh)

//XMLEncryption.cs

//NOTE: must add a project reference to System.Security

using System;using System.IO;using System.Text;using System.Xml;using System.Security.Cryptography;using System.Security.Cryptography.Xml;

32

class XMLEncryption{

static void Main(string[] args){

//create participantsSender sender = new Sender();Receiver receiver = new Receiver();

//establish public and private RSA key informationreceiver.EstablishXmlRsaParameters(

"RsaIncludePrivateParams.xml","RsaExcludePrivateParams.xml");

The receiver creates RSA keys and places them intwo files – one for the receiver and one for the sender.

33

//create original XML document to be encryptedsender.CreateOriginalXmlDocument(

"OriginalInvoice.xml");

//create session key and encrypt via RSA public keybyte [] IV = sender.CreateAndEncryptXmlSessionKey(

"RsaExcludePrivateParams.xml","SessionKeyExchange.xml");

The sender creates an XML document.

And generates a symmetric encryption key that is encryptedwith the public key of the receiver. E(SK)

34

//encrypt original XML document with session keysender.EncryptOriginalXmlDocument(

"OriginalInvoice.xml","RsaExcludePrivateParams.xml","SessionKeyExchange.xml", // no need"EncryptedInvoice.xml");

//encrypt XML document with session keyreceiver.DecryptXmlDocument(

"EncryptedInvoice.xml","RsaIncludePrivateParams.xml","SessionKeyExchange.xml","DecryptedCreditInfo.xml",IV);

}}

The sender encrypts sensitive parts of the document.

The receiver decrypts the session key and is then ableto decrypt the document.

35

class Sender{

public void CreateOriginalXmlDocument(String originalFilename){

//establish the original XML documentXmlDocument xmlDoc = new XmlDocument();xmlDoc.PreserveWhitespace = true;xmlDoc.LoadXml(

"<invoice>\n" +" <items>\n" +" <item>\n" +" <desc>Deluxe corncob pipe</desc>\n" +" <unitprice>14.95</unitprice>\n" +" <quantity>1</quantity>\n" +" </item>\n" +" </items>\n" +" <creditinfo>\n" +" <cardnumber>0123456789</cardnumber>\n" +" <expiration>01/06/2005</expiration>\n" +" <lastname>Finn</lastname>\n" +" <firstname>Huckleberry</firstname>\n" +" </creditinfo>\n" +"</invoice>\n");

The sender builds the document the hard way.

This part is sensitive.

36

//write original XML document to fileStreamWriter file =

new StreamWriter(originalFilename);file.Write(xmlDoc.OuterXml);file.Close();

//let the user know what happenedConsole.WriteLine(

"Original XML document written to:\n\t" + originalFilename);

}

Write the “hand built” XML to a file.

37

public byte [] CreateAndEncryptXmlSessionKey(String rsaExcludePrivateParamsFilename,String keyFilename)

{//obtain session key for 3DES bulk encryptionTripleDESCryptoServiceProvider tripleDES =

new TripleDESCryptoServiceProvider();

//store IV and Key for sender encryptionIV = tripleDES.IV;Key = tripleDES.Key;

//fetch public only RSA parameters from XML StreamReader fileRsaParams = new StreamReader(

rsaExcludePrivateParamsFilename);String rsaExcludePrivateParamsXML =

fileRsaParams.ReadToEnd();fileRsaParams.Close();

The sender creates the session key.

Before encryptingthe key it needs the public key of the receiver.

38

//RSA encrypt session key RSACryptoServiceProvider rsa =

new RSACryptoServiceProvider(); rsa.FromXmlString(rsaExcludePrivateParamsXML);

byte[] keyEncryptedBytes = rsa.Encrypt(tripleDES.Key, false);

//store encrypted 3DES session key in Base64 string String keyEncryptedString = Convert.ToBase64String(

keyEncryptedBytes);

//create XML document for 3DES session key exchange XmlDocument xmlKeyDoc = new XmlDocument();

xmlKeyDoc.PreserveWhitespace = true;

The sender encrypts the DES session key.

And builds an XML documentto hold it.

39

//add EncryptedKey element to key XML XmlElement xmlEncryptedKey =

xmlKeyDoc.CreateElement("EncryptedKey"); xmlKeyDoc.AppendChild(xmlEncryptedKey); XmlAttribute xmlCarriedKeyName =

xmlKeyDoc.CreateAttribute("CarriedKeyName"); xmlCarriedKeyName.Value = "My 3DES Session Key"; xmlEncryptedKey.Attributes.Append(

xmlCarriedKeyName);

So far we have…<EncryptedKey CarriedKeyName="My 3DES Session Key">

40

//add the EncryptionMethod element to key XML XmlElement xmlEncryptionMethod =

xmlKeyDoc.CreateElement("EncryptionMethod"); xmlEncryptedKey.AppendChild(xmlEncryptionMethod); XmlAttribute xmlAlgorithm =

xmlKeyDoc.CreateAttribute("Algorithm"); xmlAlgorithm.Value = "http://www.w3.org/2001/04/xmlenc#rsa-1_5"; xmlEncryptionMethod.Attributes.Append(

xmlAlgorithm);

<EncryptedKey CarriedKeyName="My 3DES Session Key">

<EncryptionMethod Algorithm= "http://www.w3.org/2001/04/xmlenc#rsa-1_5" />

41

//add KeyInfo element to key XMLXmlElement xmlKeyInfo =

xmlKeyDoc.CreateElement("ds", "KeyInfo","http://www.w3.org/2000/09/xmldsig#");

xmlEncryptedKey.AppendChild(xmlKeyInfo);

//add KeyName element to key XMLXmlElement xmlKeyName =

xmlKeyDoc.CreateElement("ds", "KeyName", null);xmlKeyName.InnerText = "My Private Key";xmlKeyInfo.AppendChild(xmlKeyName);

<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><KeyName>My Private Key</KeyName></ds:KeyInfo>

42

//add CipherData element to key XMLXmlElement xmlCipherData =

xmlKeyDoc.CreateElement("CipherData");xmlEncryptedKey.AppendChild(xmlCipherData);

<CipherData>

43

//add CipherValue element to key XMLXmlElement xmlCipherValue =

xmlKeyDoc.CreateElement("CipherValue");

xmlCipherValue.InnerText = keyEncryptedString;xmlCipherData.AppendChild(xmlCipherValue);

<CipherValue>Shy7Nzo/ctBPAhwubFiAYpNNB2CuM4TpCUozP2oQZrEMT03OEzspgkBaItai8ImBUiSUT1KlPCbawG2edz40ISgJ+G+Sl4m6ZNmL0//gqs4/7eUyLY0rSFeCnW9hKU/hr0r4wDJaKiI+hS68OTHeBBcGLCyFEPSCQXeqbnvqQBo=</CipherValue></CipherData></EncryptedKey>

44

//save key XML informationxmlKeyDoc.Save(keyFilename);

//let the user know what happenedConsole.WriteLine(

"Encrypted Session Key XML written to:\n\t" + keyFilename);

return IV; //needed by receiver too}

The sender has placed an encrypted session key on file.

45

public void EncryptOriginalXmlDocument(String originalFilename,String rsaExcludePrivateParamsFilename,String keyFilename,String encryptedFilename)

{

Original XML Document

Receiver’s publickey

Encrypted symmetric keyfile name??

Document partially encrypted with session key

46

//load XML document to be encryptedXmlDocument xmlDoc = new XmlDocument();xmlDoc.PreserveWhitespace = true;xmlDoc.Load(originalFilename);

//get creditinfo node plaintext bytes to encryptXmlElement xmlCreditinfo =

(XmlElement)xmlDoc.SelectSingleNode("invoice/creditinfo");

byte[] creditinfoPlainbytes = Encoding.UTF8.GetBytes(xmlCreditinfo.OuterXml);

Load the documentholding sensitivetag

Find the tag

Get the bytes and include the tag name.

47

//create 3DES algorithm object for bulk encryptionTripleDESCryptoServiceProvider tripleDES =

new TripleDESCryptoServiceProvider();

Getting ready for symmetric encryption…

48

//establish crypto stream using 3DES algorithmMemoryStream ms = new MemoryStream();CryptoStream cs = new CryptoStream(

ms,tripleDES.CreateEncryptor(Key, IV),CryptoStreamMode.Write);

//write creditinfo plaintext to crypto streamcs.Write(

creditinfoPlainbytes, 0, creditinfoPlainbytes.Length);

cs.Close();

Use the sameKey that weEncryptedbefore

Encrypt the sensitive tag with thesession key.

49

//get creditinfo ciphertext from crypto streambyte[] creditinfoCipherbytes = ms.ToArray();ms.Close();String creditinfoCiphertext =

Convert.ToBase64String(creditinfoCipherbytes);

Get the encrypted bytes and convert them to base 64

50

//create EncryptedData in XML fileXmlElement xmlEncryptedData =

xmlDoc.CreateElement("EncryptedData");XmlAttribute xmlType =

xmlDoc.CreateAttribute("Type");xmlType.Value =

"http://www.w3.org/2001/04/xmlenc#Element";xmlEncryptedData.Attributes.Append(xmlType);

//add KeyInfo elementXmlElement xmlKeyInfo =

xmlDoc.CreateElement("ds", "KeyInfo","http://www.w3.org/2000/09/xmldsig#");

xmlEncryptedData.AppendChild(xmlKeyInfo);

Homework: Trace through the construction of this document.

51

//add KeyName elementXmlElement xmlKeyName =

xmlDoc.CreateElement("ds", "KeyName",null);xmlKeyName.InnerText = "My 3DES Session Key";xmlKeyInfo.AppendChild(xmlKeyName);

//add CipherData elementXmlElement xmlCipherData =

xmlDoc.CreateElement("CipherData");xmlEncryptedData.AppendChild(xmlCipherData);

//add CipherValue element with encrypted creditinfoXmlElement xmlCipherValue =

xmlDoc.CreateElement("CipherValue");xmlCipherValue.InnerText = creditinfoCiphertext;xmlCipherData.AppendChild(xmlCipherValue);

52

//replace original node with the encrypted nodexmlCreditinfo.ParentNode.ReplaceChild(

xmlEncryptedData, xmlCreditinfo);

//save XML to encrypted filexmlDoc.Save(encryptedFilename);

//let the user know what happenedConsole.WriteLine(

"Encrypted XML document written to:\n\t" + encryptedFilename);

}

//information sender needs across method callsstatic byte [] IV;static byte [] Key;

}

The encrypted document is built. The receiver needsto read it…

53

What does the receiver need ?

• The encrypted document

• The encrypted session key

54

class Receiver {

public void EstablishXmlRsaParameters(String rsaIncludePrivateParamsFilename, String rsaExcludePrivateParamsFilename)

{//create RSA object with new key pairRSACryptoServiceProvider rsa =

new RSACryptoServiceProvider();

//store public and private RSA key params in XMLStreamWriter fileRsaIncludePrivateParams

= new StreamWriter(rsaIncludePrivateParamsFilename);

fileRsaIncludePrivateParams.Write(rsa.ToXmlString(true));

fileRsaIncludePrivateParams.Close();

Executedbefore anything else

The receiverneeds the publicand private keys.

55

//store public only RSA key params in XMLStreamWriter fileRsaExcludePrivateParams =

new StreamWriter(rsaExcludePrivateParamsFilename);

fileRsaExcludePrivateParams.Write(rsa.ToXmlString(false));

fileRsaExcludePrivateParams.Close();

//let the user know what happenedConsole.WriteLine(

"RSA parameters written to:\n\t" + rsaIncludePrivateParamsFilename + "\n\t" +rsaExcludePrivateParamsFilename);

}

The sender needs the public keys.

Two files written.

56

public void DecryptXmlDocument(String encryptedFilename,String rsaIncludePrivateParamsFilename,String keyFilename,String decryptedFilename,byte [] IV)

{//load encrypted XML documentXmlDocument xmlDoc = new XmlDocument();xmlDoc.PreserveWhitespace = true;xmlDoc.Load(encryptedFilename);

//get creditinfo node ciphertext bytes to decryptXmlElement xmlEncryptedData =

(XmlElement)xmlDoc.SelectSingleNode("invoice/EncryptedData");

Decrypt – get the document and find the encrypted element

57

XmlElement xmlCipherValue = (XmlElement)xmlEncryptedData.SelectSingleNode("CipherData/CipherValue");

byte[] creditinfoCipherbytes = Convert.FromBase64String( xmlCipherValue.InnerText);

//load XML key documentXmlDocument xmlKeyDoc = new XmlDocument();xmlKeyDoc.PreserveWhitespace = true;xmlKeyDoc.Load(keyFilename);

//get encrypted session key bytesXmlElement xmlKeyCipherValue =

(XmlElement)xmlKeyDoc.SelectSingleNode("EncryptedKey/CipherData/CipherValue");

byte[] xmlKeyCipherbytes = Convert.FromBase64String( xmlKeyCipherValue.InnerText);

Get the encryptedsymmetric key..

..as an array of bytes

Get encryptedbytes

58

//fetch public only RSA parameters from XML StreamReader fileRsaParams = new StreamReader(

rsaIncludePrivateParamsFilename);

String rsaIncludePrivateParamsXML = fileRsaParams.ReadToEnd();

fileRsaParams.Close();

//RSA decrypt 3DES session keyRSACryptoServiceProvider rsa =

new RSACryptoServiceProvider();rsa.FromXmlString(rsaIncludePrivateParamsXML);

byte[] keyPlainBytes = rsa.Decrypt(xmlKeyCipherbytes, false);

//create 3DES algorithm object for bulk encryptionTripleDESCryptoServiceProvider tripleDES =

new TripleDESCryptoServiceProvider();

Get the RSAPrivate key

Decrypt the sessionkey

Prepare to use DESdecryption

59

//establish crypto stream using 3DES algorithmMemoryStream ms = new MemoryStream(

creditinfoCipherbytes);CryptoStream cs = new CryptoStream(

ms,tripleDES.CreateDecryptor(keyPlainBytes, IV),CryptoStreamMode.Read);

//read creditinfo plaintext from crypto streambyte[] creditinfoPlainbytes =

new Byte[creditinfoCipherbytes.Length];cs.Read(

creditinfoPlainbytes, 0, creditinfoPlainbytes.Length);

cs.Close();ms.Close();

String creditinfoPlaintext = Encoding.UTF8.GetString(creditinfoPlainbytes);

Operate on theSensitive data

Now it’s in theclear

60

//Create a document fragment. XmlDocumentFragment docFrag = xmlDoc.CreateDocumentFragment(); //Set the contents of the document fragment. docFrag.InnerXml = creditinfoPlaintext;

//Add the children of the document fragment to the //original document. xmlDoc.DocumentElement.AppendChild(docFrag);

Console.WriteLine("Display the modified XML..."); Console.WriteLine(xmlDoc.OuterXml);

XmlElement invoiceTag = (XmlElement)xmlDoc.SelectSingleNode("invoice");

invoiceTag.ReplaceChild(docFrag,xmlEncryptedData);

Homework 2: Trace this document construction

61

//write decrypted XML node to fileStreamWriter fileplaintext =

new StreamWriter(decryptedFilename);fileplaintext.Write(xmlDoc.OuterXml);

fileplaintext.Close();

//let the user know what happenedConsole.WriteLine(

"Decrypted XML credit info written to:\n\t" + decryptedFilename);

}}