1 xml signature 95-733 internet technologies. 2 xml signature an ietf/w3c recommendation

75
1 XML Signature 95-733 Internet Technologies

Post on 21-Dec-2015

219 views

Category:

Documents


0 download

TRANSCRIPT

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

1

XML Signature

95-733 Internet Technologies

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

2

XML Signature

An IETF/W3C Recommendation

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

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

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

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

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

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

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.

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

7

We may have many references

<Reference>

pointer, digest method, digest value

</Reference>

:

<Reference>

pointer, digest method, digest value

</Reference>

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

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>

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

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…

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

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>

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

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>

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

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?

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

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

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

14

Using IBM’s XML Security Suite

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

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>

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

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

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

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

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

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>

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

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

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

20

</SignedInfo> <SignatureValue>

Gll1H/uplOwfaX3j7ST6UqQlc92Hx2nsCdN2KWz32CW0D4hH64n32v/InkGux1dYgTya6S4s55iHqZEjDpH2I359H4PAxBYYXJj4LUBNxAFxUcDy6xrEUbLnKeutT5pf1DBSmxg9Cp3PO5Rs36nVN8GVfnFl1M86WQd19/RsAnA=

</SignatureValue>

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

21

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

7V5eyhVaw0clED11H6PTPoKQA1VxrLAugU3QxKA0hbbUOiavFbqCdc6Z+Fe9JZFMkS

Iqdl+khwWwd+AIsRyrN4V2DWm1f+xyYQf6bdZgCaVVgkST1BpQxBTgNKRcS5VbLrXf

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

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

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>

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

23

MIICPDCCAaUCBD6Ik40wDQYJKoZIhvcNAQEEBQAwZTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlBB

MQwwCgYDVQQHEwNQZ2gxDDAKBgNVBAoTA0NNVTEVMBMGA1UECxMMSGVpbnogU2Nob29sMRYwFAYD

VQQDEw1NaWtlIE1jQ2FydGh5MB4XDTAzMDMzMTE5MTQyMVoXDTAzMDYyOTE5MTQyMVowZTELMAkG

A1UEBhMCVVMxCzAJBgNVBAgTAlBBMQwwCgYDVQQHEwNQZ2gxDDAKBgNVBAoTA0NNVTEVMBMGA1UE

CxMMSGVpbnogU2Nob29sMRYwFAYDVQQDEw1NaWtlIE1jQ2FydGh5MIGfMA0GCSqGSIb3DQEBAQUA

A4GNADCBiQKBgQDtXl7KFVrDRyUQPXUfo9M+gpADVXGssC6BTdDEoDSFttQ6Jq8VuoJ1zpn4V70l

kUyRIip2X6SHBbB34AixHKs3hXYNabV/7HJhB/pt1mAJpVWCRJPUGlDEFOA0pFxLlVsutd/gxdvl

NuED56jVBuvYiOVXXRottWFST+D7KVqD6QIDAQABMA0GCSqGSIb3DQEBBAUAA4GBAMpUaA8Cw8mK

Qn408KuV4xrTciEEcTLNniDGnf8d9W1fR4veqhKz8L8+886+4bNS5Wih+1oEC5k/da23QicpTdXf

UyA1c29Zu3cGU4ulUfhFPWv0IgdpI63KQt9QwsuTxWck5dAta2+KWWTv85IhByHXgoaDlvJ65JjT

87nAPAI3

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

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

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

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

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

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>

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

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)

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

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>

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

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>

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

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>

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

31

<SignatureValue>

Ptysg8WdHI2mxwryOOt5I9r9qZm/2gNFNOJyH1Wak4nCUegRpe72tWnsigAKZyopmgUSH3TG

aGGQF1BTSvk3JUUY/ljrw+5FpTpf3hgZBi7GSWf6WtXqZvMYGUKIlvR/421MZg7P9XRUyy37

ZUzQHtmCYkBorEkEx1J4CYB0G2c=

</SignatureValue>

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

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>

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

33

.NET Example

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

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

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

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

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

36

The RSA Public key in XML

<RSAKeyValue><Modulus>z9zv0HMRK44BrjYIQtmKlDkA6WnQCIVOYmOj

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

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

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

37

The RSA Public/Private Key data in XML

<RSAKeyValue>

<Modulus>

z9zv0HMRK44BrjYIQtmKlDkA6WnQCIVOYmOjy/eKhFqXJM024JybC/5hOCQoYRRo5iYRopIV4gBZUBSolxgk8jIr38iO84lDoSisPl3ikcob/aCuhPe8jSl4zbKpiJ+rqQE8rSNJ3XDPDVIiRoDbSRbn04x210tjYNMbePw0RQk=

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

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

38

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

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

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

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

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>

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

40

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

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

41

The Original Invoice

<invoice><items> <item>

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

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

42

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

</invoice>

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

43

The Encrypted Invoice

<invoice><items> <item>

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

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

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>

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

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;

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

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.

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

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)

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

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.

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

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.

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

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.

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

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.

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

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.

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

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

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

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

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

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>

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

56

//add CipherData element to key XMLXmlElement xmlCipherData =

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

<CipherData>

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

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>

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

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.

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

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

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

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.

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

61

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

new TripleDESCryptoServiceProvider();

Getting ready for symmetric encryption…

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

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.

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

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

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

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

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

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

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

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…

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

67

What does the receiver need ?

• The encrypted document

• The encrypted session key

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

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.

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

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.

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

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

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

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

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

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

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

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

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

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

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

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

}}