1.net cryptography object oriented programming iii

61
1 .NET Cryptography Object Oriented Programming III

Upload: hector-oneal

Post on 01-Jan-2016

221 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1.NET Cryptography Object Oriented Programming III

1

.NET Cryptography

Object Oriented Programming III

Page 2: 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

Page 3: 1.NET Cryptography Object Oriented Programming III

3

Not a replacement for SSL

• XML Encryption adds

Encrypting part of the data being exchanged

Secure sessions between more than two parties

Page 4: 1.NET Cryptography Object Oriented Programming III

4

General Form 1

<EncryptedData>

<CipherData>

<CipherValue>

Cipher Text Gibberish in Base 64

</CipherValue>

</CipherData>

</EncryptedData>

Page 5: 1.NET Cryptography Object Oriented Programming III

5

General Form 2

<EncryptedData>

<CipherData>

<CipherReference>

pointer (URL) to gibberish

</CipherReference>

</CipherData>

</EncryptedData>

Page 6: 1.NET Cryptography Object Oriented Programming III

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

Page 7: 1.NET Cryptography Object Oriented Programming III

7

General Example (1)

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

Page 8: 1.NET Cryptography Object Oriented Programming III

8

General Example (2)

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

Page 9: 1.NET Cryptography Object Oriented Programming III

9

General Example (3)

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

</EncryptedData></Finacial>

</MedInfo>

Page 10: 1.NET Cryptography Object Oriented Programming III

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>

Page 11: 1.NET Cryptography Object Oriented Programming III

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

Page 12: 1.NET Cryptography Object Oriented Programming III

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

Page 13: 1.NET Cryptography Object Oriented Programming III

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>

Page 14: 1.NET Cryptography Object Oriented Programming III

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>

Page 15: 1.NET Cryptography Object Oriented Programming III

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>

Page 16: 1.NET Cryptography Object Oriented Programming III

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>

Page 17: 1.NET Cryptography Object Oriented Programming III

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>

Page 18: 1.NET Cryptography Object Oriented Programming III

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>

Page 19: 1.NET Cryptography Object Oriented Programming III

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>

Page 20: 1.NET Cryptography Object Oriented Programming III

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

Page 21: 1.NET Cryptography Object Oriented Programming III

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

Page 22: 1.NET Cryptography Object Oriented Programming III

22

The RSA Public key in XML

<RSAKeyValue><Modulus>z9zv0HMRK44BrjYIQtmKlDkA6WnQCIVOYmOj

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

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

Page 23: 1.NET Cryptography Object Oriented Programming III

23

The RSA Public/Private Key Pair

<RSAKeyValue>

<Modulus>

z9zv0HMRK44BrjYIQtmKlDkA6WnQCIVOYmOjy/eKhFqXJM024JybC/5hOCQoYRRo5iYRopIV4gBZUBSolxgk8jIr38iO84lDoSisPl3ikcob/aCuhPe8jSl4zbKpiJ+rqQE8rSNJ3XDPDVIiRoDbSRbn04x210tjYNMbePw0RQk=

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

Page 24: 1.NET Cryptography Object Oriented Programming III

24

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

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

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

Page 25: 1.NET Cryptography Object Oriented Programming III

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>

Page 26: 1.NET Cryptography Object Oriented Programming III

26

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

Page 27: 1.NET Cryptography Object Oriented Programming III

27

The Original Invoice

<invoice><items> <item>

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

Page 28: 1.NET Cryptography Object Oriented Programming III

28

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

</invoice>

Page 29: 1.NET Cryptography Object Oriented Programming III

29

The Encrypted Invoice

<invoice><items><item>

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

Page 30: 1.NET Cryptography Object Oriented Programming III

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>

Page 31: 1.NET Cryptography Object Oriented Programming III

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;

Page 32: 1.NET Cryptography Object Oriented Programming III

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.

Page 33: 1.NET Cryptography Object Oriented Programming III

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)

Page 34: 1.NET Cryptography Object Oriented Programming III

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.

Page 35: 1.NET Cryptography Object Oriented Programming III

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.

Page 36: 1.NET Cryptography Object Oriented Programming III

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.

Page 37: 1.NET Cryptography Object Oriented Programming III

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.

Page 38: 1.NET Cryptography Object Oriented Programming III

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.

Page 39: 1.NET Cryptography Object Oriented Programming III

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">

Page 40: 1.NET Cryptography Object Oriented Programming III

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" />

Page 41: 1.NET Cryptography Object Oriented Programming III

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>

Page 42: 1.NET Cryptography Object Oriented Programming III

42

//add CipherData element to key XMLXmlElement xmlCipherData =

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

<CipherData>

Page 43: 1.NET Cryptography Object Oriented Programming III

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>

Page 44: 1.NET Cryptography Object Oriented Programming III

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.

Page 45: 1.NET Cryptography Object Oriented Programming III

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

Page 46: 1.NET Cryptography Object Oriented Programming III

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.

Page 47: 1.NET Cryptography Object Oriented Programming III

47

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

new TripleDESCryptoServiceProvider();

Getting ready for symmetric encryption…

Page 48: 1.NET Cryptography Object Oriented Programming III

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.

Page 49: 1.NET Cryptography Object Oriented Programming III

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

Page 50: 1.NET Cryptography Object Oriented Programming III

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.

Page 51: 1.NET Cryptography Object Oriented Programming III

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);

Page 52: 1.NET Cryptography Object Oriented Programming III

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…

Page 53: 1.NET Cryptography Object Oriented Programming III

53

What does the receiver need ?

• The encrypted document

• The encrypted session key

Page 54: 1.NET Cryptography Object Oriented Programming III

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.

Page 55: 1.NET Cryptography Object Oriented Programming III

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.

Page 56: 1.NET Cryptography Object Oriented Programming III

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

Page 57: 1.NET Cryptography Object Oriented Programming III

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

Page 58: 1.NET Cryptography Object Oriented Programming III

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

Page 59: 1.NET Cryptography Object Oriented Programming III

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

Page 60: 1.NET Cryptography Object Oriented Programming III

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

Page 61: 1.NET Cryptography Object Oriented Programming III

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);

}}