1 XML Signature 95-733 Internet Technologies. 2 XML Signature An IETF/W3C Recommendation

Preview:

Citation preview

1

XML Signature

95-733 Internet Technologies

2

XML Signature

An IETF/W3C Recommendation

3

XML Signature

• XML Signatures are digital signatures used in XML transactions

• May be used to sign only a portion of an XML document. The document might have

a long history with different parts holding different signatures

• The signature may apply to XML or non-XML data

4

Referencing What is Signed

• The XML Signature may hold a URI

• The signature may be a sibling of what is signed.

• The signature may be a parent of what is signed.

• The signature may be a child of what is signed

5

The Reference Element

• Each signed resource is specified with

a <Reference> element

• A typical <Reference> element will contain

- a pointer to what is signed

- a digest method (for example SHA1)

- and a digest value of the signed data in base 64 notation

6

The <Reference> Element

<Reference URI = “http://.../po.xml”> <DigestMethod>….</DigestMethod> <DigestValue> calculated digest of po.xml </DigestValue> </Reference>

This is the locationof the document beingsigned.

7

We may have many references

<Reference>

pointer, digest method, digest value

</Reference>

:

<Reference>

pointer, digest method, digest value

</Reference>

8

Place Within a SignedInfo Element

<SignedInfo> <CanonicalizationMethod> algorithm used on SignedInfo element <SignatureMethod> for example dsa-sha1 <Reference> pointer, digest method, digest value </Reference> <Reference> pointer, digest method, digest value </Reference>

</SignedInfo>

9

Compute Digest of SignedInfo

<SignedInfo>

<CanonicalizationMethod> algorithm used on SignedInfo element

<SignatureMethod> for example dsa-sha1

<Reference>

pointer, digest method, digest value

</Reference>

<Reference>

pointer, digest method, digest value

</Reference>

</SignedInfo>

Sign the digest and place value in a SignatureValue element…

10

Enclose in a Signature Element

<SignedInfo> <CanonicalizationMethod> algorithm used on SignedInfo element <SignatureMethod> for example dsa-sha1 <Reference> pointer, method, digest value </Reference> <Reference> pointer, method, digest value </Reference></SignedInfo><SignatureValue>Base 64 signature of the SignedInfo Element</SignatureValue>

<Signature>

</Signature>

11

We may include KeyInfo

<SignedInfo> <Canonicalization> <SignatureMethod> <Reference>… <Reference>…</SignedInfo><SignatureValue>Base 64 signature of the SignedInfo Element</SignatureValue>

<KeyInfo> <X509Data> <X509SubjectName>CN=Cristina McCarthy, O=CMU,… <X509Certificate> base 64 public key and identity signed by

a CA </X509Certificate> </X509Data></KeyInfo>

<Signature>

</Signature>

12

What Can Mallory Do?

• Can she modify the CA signed certificate so that someone else appears to have signed the document?

• Can she modify what is being pointed by the reference element?

• Can she change the canonicalization method?

• Can she change the contents of the signature method tag?

13

Verification

1. Canonicalize the SignedInfo element.2. Compute the digest of the SignedInfo element using the method described within it3. Compare the above value with that value got from applying the signer’s public key to the value in the SignatureValue element4. Compute digests of referenced items and compare those digests found within each reference tag

14

Using IBM’s XML Security Suite

15

Suppose we want to sign a gradebook

Gradebook.xml

<?xml version="1.0" encoding="UTF-8"?><GradeBook> <Student> <Score>100</Score> <Score>89</Score> </Student></GradeBook>

16

We need keys

D:\..\95-804\IBMXMLSecuritySuite\SampleSign2>

keytool -genkey -keyalg RSA -keystore test.keystore

-dname "CN=Mike McCarthy, OU=Heinz School,

O=CMU, L=Pgh, S=PA, C=US" -alias mjm

-storepass sesame -keypass sesame

Creates test.keystore holding keys and a self-signed certificate

17

Run XSS4J’s SampleSign2

D:\...\95-804\IBMXMLSecuritySuite\

SampleSign2>java SampleSign2 mjm

sesame sesame

-embxml gradebook.xml > signature.xml

Key store: test.keystore

Sign: 851ms

18

Examine Signature.xml<Signature xmlns="http://www.w3.org/2000/09/xmldsig#"> <SignedInfo>

<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"></CanonicalizationMethod>

<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></SignatureMethod>

19

<Reference URI="#Res0"> <Transforms> <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-

c14n-20010315"> </Transform> </Transforms> <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"> </DigestMethod> <DigestValue>m6f9xhOc4iEXokD/29V9EsdY3yI= </DigestValue> </Reference>

We are signing resource 0

20

</SignedInfo> <SignatureValue>

Gll1H/uplOwfaX3j7ST6UqQlc92Hx2nsCdN2KWz32CW0D4hH64n32v/InkGux1dYgTya6S4s55iHqZEjDpH2I359H4PAxBYYXJj4LUBNxAFxUcDy6xrEUbLnKeutT5pf1DBSmxg9Cp3PO5Rs36nVN8GVfnFl1M86WQd19/RsAnA=

</SignatureValue>

21

<KeyInfo> <KeyValue> <RSAKeyValue> <Modulus>

7V5eyhVaw0clED11H6PTPoKQA1VxrLAugU3QxKA0hbbUOiavFbqCdc6Z+Fe9JZFMkS

Iqdl+khwWwd+AIsRyrN4V2DWm1f+xyYQf6bdZgCaVVgkST1BpQxBTgNKRcS5VbLrXf

4MXb5TbhA+eo1Qbr2IjlV10aLbVhUk/g+ylag+k= </Modulus> <Exponent>AQAB</Exponent> </RSAKeyValue> </KeyValue>

22

<X509Data> <X509IssuerSerial> <X509IssuerName>CN=Mike McCarthy,OU=Heinz School,O=CMU,L=Pgh,ST=PA,C=US </X509IssuerName> <X509SerialNumber>1049138061 </X509SerialNumber> </X509IssuerSerial> <X509SubjectName>CN=Mike McCarthy,OU=Heinz School,O=CMU,L=Pgh,ST=PA,C=US </X509SubjectName> <X509Certificate>

23

MIICPDCCAaUCBD6Ik40wDQYJKoZIhvcNAQEEBQAwZTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlBB

MQwwCgYDVQQHEwNQZ2gxDDAKBgNVBAoTA0NNVTEVMBMGA1UECxMMSGVpbnogU2Nob29sMRYwFAYD

VQQDEw1NaWtlIE1jQ2FydGh5MB4XDTAzMDMzMTE5MTQyMVoXDTAzMDYyOTE5MTQyMVowZTELMAkG

A1UEBhMCVVMxCzAJBgNVBAgTAlBBMQwwCgYDVQQHEwNQZ2gxDDAKBgNVBAoTA0NNVTEVMBMGA1UE

CxMMSGVpbnogU2Nob29sMRYwFAYDVQQDEw1NaWtlIE1jQ2FydGh5MIGfMA0GCSqGSIb3DQEBAQUA

A4GNADCBiQKBgQDtXl7KFVrDRyUQPXUfo9M+gpADVXGssC6BTdDEoDSFttQ6Jq8VuoJ1zpn4V70l

kUyRIip2X6SHBbB34AixHKs3hXYNabV/7HJhB/pt1mAJpVWCRJPUGlDEFOA0pFxLlVsutd/gxdvl

NuED56jVBuvYiOVXXRottWFST+D7KVqD6QIDAQABMA0GCSqGSIb3DQEBBAUAA4GBAMpUaA8Cw8mK

Qn408KuV4xrTciEEcTLNniDGnf8d9W1fR4veqhKz8L8+886+4bNS5Wih+1oEC5k/da23QicpTdXf

UyA1c29Zu3cGU4ulUfhFPWv0IgdpI63KQt9QwsuTxWck5dAta2+KWWTv85IhByHXgoaDlvJ65JjT

87nAPAI3

24

</X509Certificate> </X509Data> </KeyInfo> <dsig:Object xmlns="" xmlns:dsig="http://www.w3.org/2000/09/xmldsig#" Id="Res0">

<GradeBook> <Student> <Score>100</Score> <Score>89</Score> </Student> </GradeBook> </dsig:Object></Signature>

The resource 0 object

25

Verify the signatureD:\McCarthy\www\95-804\IBMXMLSecuritySuite\SampleSign2>java VerifyCUI < signature.xml

The signature has a KeyValue element.The signature has one or more X509Data elements.Checks an X509Data:1 certificate(s).

Certificate Information: Version: 1 Validity: OK SubjectDN: CN=Mike McCarthy, OU=Heinz School, O=CMU, L=Pgh, ST=PA, C=US IssuerDN: CN=Mike McCarthy, OU=Heinz School, O=CMU, L=Pgh, ST=PA, C=US Serial#: 0x3e88938dTime to verify: 490 [msec]Core Validity: OKSignature Validity: OK[0] "#Res0" OK

26

Let’s change the low grade!

<dsig:Object xmlns="" xmlns:dsig="http://www.w3.org/2000/09/xmldsig#" Id="Res0">

<GradeBook> <Student> <Score>100</Score> <Score>100</Score> </Student></GradeBook></dsig:Object>

27

And run verify…D:\McCarthy\www\95-804\IBMXMLSecuritySuite\SampleSign2>java VerifyCUI <

signature.xml

The signature has a KeyValue element.The signature has one or more X509Data elements.Checks an X509Data:1 certificate(s).

Certificate Information: Version: 1 Validity: OK SubjectDN: CN=Mike McCarthy, OU=Heinz School, O=CMU, L=Pgh, ST=PA, C=US IssuerDN: CN=Mike McCarthy, OU=Heinz School, O=CMU, L=Pgh, ST=PA, C=US Serial#: 0x3e88938dTime to verify: 521 [msec]Core Validity: NGSignature Validity: OK[0] "#Res0" NG: Digest value mismatch: calculated: tfVyHns8wRB6l/HDU2dXZkzf+7Q=Exception in thread "main" java.lang.RuntimeException: Core Validity: NG at dsig.VerifyCUI.main(VerifyCUI.java:137)

28

Another Example PO.XML

<?xml version="1.0" encoding="UTF-8"?><PurchaseOrder xmlns="urn:purchase-order"> <Customer> <Name>Robert Smith</Name> <CustomerId>788335</CustomerId> </Customer> <Item partNum="C763"> <ProductId>6883-JF3</ProductId> <Quantity>3</Quantity> <ShipDate>2002-09-03</ShipDate> <Name>ThinkPad X20</Name> </Item></PurchaseOrder>

29

PO After Signing<?xml version='1.0' encoding='UTF-8'?><SignedPurchaseOrder>

<PurchaseOrder id="id0" xmlns="urn:purchase-order"> <Customer> <Name>Robert Smith</Name> <CustomerId>788335</CustomerId> </Customer> <Item partNum="C763"> <ProductId>6883-JF3</ProductId> <Quantity>3</Quantity> <ShipDate>2002-09-03</ShipDate> <Name>ThinkPad X20</Name> </Item> </PurchaseOrder>

30

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#"> <SignedInfo> <CanonicalizationMethod

Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/> <SignatureMethod

Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/> <Reference URI="#id0"> <DigestMethod

Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>

<DigestValue>UfeiscUCL7QkhZtRDLWDPWLpVlA=</DigestValue> </Reference> </SignedInfo>

31

<SignatureValue>

Ptysg8WdHI2mxwryOOt5I9r9qZm/2gNFNOJyH1Wak4nCUegRpe72tWnsigAKZyopmgUSH3TG

aGGQF1BTSvk3JUUY/ljrw+5FpTpf3hgZBi7GSWf6WtXqZvMYGUKIlvR/421MZg7P9XRUyy37

ZUzQHtmCYkBorEkEx1J4CYB0G2c=

</SignatureValue>

32

<KeyInfo>

<X509Data> <X509Certificate> MIIDGjCCAoOgAwIBAgICAQAwDQYJKoZIhvcNAQEFBQAwXzELMAkGA1UEBhMCSlAxETAPBgNVBAgT CEthbmFnYXdhMQ8wDQYDVQQHEwZZYW1hdG8xDDAKBgNVBAoTA0lCTTEMMAoGA1UECxMDVFJMMRAw

DgYDVQQDEwdUZXN0IENBMB4XDTAxMTAwMTA3MTYxMFoXDTExMTAwMTA3MTYxMFowUDELMAkGA1UE

BhMCSlAxETAPBgNVBAgTCEthbmFnYXdhMQwwCgYDVQQKEwNJQk0xDDAKBgNVBAsTA1RSTDESMBAG A1UEAxMJU2lnbmF0dXJlMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvnFQiPEJnUZnkmzoc MjsseD8ms9HBgasZR0VOAvsby5aajsm9CtB18dDCemDXZ2YjBdprX+epfF4SLNP5ankfphhr9QXA NJdCKpyF3jPoydckle7E7gI9w3Q4NDa4ryVOuIS2qev6jlE7OVPqiXIDVlCH4u6GbIoJEpJ57yzx

dQIDAQABo4HzMIHwMAkGA1UdEwQCMAAwCwYDVR0PBAQDAgXgMCwGCWCGSAGG+EIBDQQfFh1PcGVu

U1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUYapFv9MvQ9NNn1Q7zgzqka4XORsw gYgGA1UdIwSBgDB+gBR7FuT9bLBj3vVsgAzIeYa4hBUZBaFjpGEwXzELMAkGA1UEBhMCSlAxETAP BgNVBAgTCEthbmFnYXdhMQ8wDQYDVQQHEwZZYW1hdG8xDDAKBgNVBAoTA0lCTTEMMAoGA1UECxMD VFJMMRAwDgYDVQQDEwdUZXN0IENBggEAMA0GCSqGSIb3DQEBBQUAA4GBALFzGDXMzxJvOnCdJCMZ 2NsZdz1+wmoYyejB5J6Ch2ygdPeibMnW/CiYKCTWBhpEgxEqr1BNlgSVqA6nyvjHsVIvgBfwx37D hJ5hz4azpWu1X22XqyU9fUqoQUtEAdM/MlLekBkprkJVb9uJXTFzzvm/3DoEiBkX/BT78YdM8eq0 </X509Certificate> </X509Data>

</KeyInfo></Signature>

</SignedPurchaseOrder>

33

.NET Example

34

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

35

.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

36

The RSA Public key in XML

<RSAKeyValue><Modulus>z9zv0HMRK44BrjYIQtmKlDkA6WnQCIVOYmOj

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

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

37

The RSA Public/Private Key data in XML

<RSAKeyValue>

<Modulus>

z9zv0HMRK44BrjYIQtmKlDkA6WnQCIVOYmOjy/eKhFqXJM024JybC/5hOCQoYRRo5iYRopIV4gBZUBSolxgk8jIr38iO84lDoSisPl3ikcob/aCuhPe8jSl4zbKpiJ+rqQE8rSNJ3XDPDVIiRoDbSRbn04x210tjYNMbePw0RQk=

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

38

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

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

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

39

The Encrypted 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>

40

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

41

The Original Invoice

<invoice><items> <item>

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

42

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

</invoice>

43

The Encrypted Invoice

<invoice><items> <item>

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

44

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

45

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;

46

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.

47

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

48

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

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

//decrypt 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.

49

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.

50

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

51

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

{//create the session key for 3DES bulk encryptionTripleDESCryptoServiceProvider tripleDES =

new TripleDESCryptoServiceProvider();

//access the 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.

52

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

53

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

54

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

55

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

56

//add CipherData element to key XMLXmlElement xmlCipherData =

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

<CipherData>

57

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

58

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

59

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

60

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

61

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

new TripleDESCryptoServiceProvider();

Getting ready for symmetric encryption…

62

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

63

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

64

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

XML Encryption

65

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

66

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

67

What does the receiver need ?

• The encrypted document

• The encrypted session key

68

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.

69

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

70

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

71

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

72

//Get RSA private key to decrypt the session key 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

73

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

74

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

Rebuild the encrypted document

75

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

}}

Recommended