XML Signature - PowerPoint PPT Presentation

About This Presentation
Title:

XML Signature

Description:

... KeyInfo The Original Invoice Deluxe corncob pipe – PowerPoint PPT presentation

Number of Views:57
Avg rating:3.0/5.0
Slides: 76
Provided by: mm6
Category:
Tags: xml | java | pipe | signature | stream

less

Transcript and Presenter's Notes

Title: XML Signature


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 ltReferencegt element
  • A typical ltReferencegt 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 ltReferencegt Element
This is the location of the document being signed.
  • ltReference URI http//.../po.xmlgt
  • ltDigestMethodgt.lt/DigestMethodgt
  • ltDigestValuegt calculated digest of
  • po.xml
  • lt/DigestValuegt
  • lt/Referencegt

7
We may have many references
  • ltReferencegt
  • pointer, digest method,
    digest value
  • lt/Referencegt
  • ltReferencegt
  • pointer, digest method,
    digest value
  • lt/Referencegt

8
Place Within a SignedInfo Element
  • ltSignedInfogt
  • ltCanonicalizationMethodgt algorithm used
    on

  • SignedInfo

  • element
  • ltSignatureMethodgt for example dsa-sha1
  • ltReferencegt
  • pointer, digest
    method, digest value
  • lt/Referencegt
  • ltReferencegt
  • pointer, digest
    method, digest value
  • lt/Referencegt
  • lt/SignedInfogt

9
Compute Digest of SignedInfo
  • ltSignedInfogt
  • ltCanonicalizationMethodgt algorithm used
    on SignedInfo element
  • ltSignatureMethodgt for example dsa-sha1
  • ltReferencegt
  • pointer, digest
    method, digest value
  • lt/Referencegt
  • ltReferencegt
  • pointer, digest
    method, digest value
  • lt/Referencegt
  • lt/SignedInfogt

Sign the digest and place value in a
SignatureValue element
10
Enclose in a Signature Element
ltSignaturegt
  • ltSignedInfogt
  • ltCanonicalizationMethodgt algorithm used
    on SignedInfo

  • element
  • ltSignatureMethodgt for example dsa-sha1
  • ltReferencegt
  • pointer, method,
    digest value
  • lt/Referencegt
  • ltReferencegt
  • pointer, method,
    digest value
  • lt/Referencegt
  • lt/SignedInfogt
  • ltSignatureValuegtBase 64 signature of the
    SignedInfo Element
  • lt/SignatureValuegt

lt/Signaturegt
11
We may include KeyInfo
ltSignaturegt
  • ltSignedInfogt
  • ltCanonicalizationgt
  • ltSignatureMethodgt
  • ltReferencegt
  • ltReferencegt
  • lt/SignedInfogt
  • ltSignatureValuegtBase 64 signature of the
    SignedInfo Element
  • lt/SignatureValuegt
  • ltKeyInfogt
  • ltX509Datagt
  • ltX509SubjectNamegtCNCristina
    McCarthy, OCMU,
  • ltX509Certificategt base 64 public
    key and identity signed by a CA
  • lt/X509Certificategt
  • lt/X509Datagt
  • lt/KeyInfogt

lt/Signaturegt
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 it
  • 3. Compare the above value with that value
  • got from applying the signers public key
  • to the value in the SignatureValue element
  • 4. Compute digests of referenced items and
  • compare those digests found within each
  • reference tag

14
Using IBMs XML Security Suite
15
Suppose we want to sign a gradebook
  • Gradebook.xml
  • lt?xml version"1.0" encoding"UTF-8"?gt
  • ltGradeBookgt
  • ltStudentgt
  • ltScoregt100lt/Scoregt
  • ltScoregt89lt/Scoregt
  • lt/Studentgt
  • lt/GradeBookgt

16
We need keys
  • D\..\95-804\IBMXMLSecuritySuite\SampleSign2gt
  • keytool -genkey -keyalg RSA -keystore
    test.keystore
  • -dname "CNMike McCarthy, OUHeinz School,
  • OCMU, LPgh, SPA, CUS" -alias mjm
  • -storepass sesame -keypass sesame

Creates test.keystore holding keys and a
self-signed certificate
17
Run XSS4Js SampleSign2
  • D\...\95-804\IBMXMLSecuritySuite\
  • SampleSign2gtjava SampleSign2 mjm
  • sesame sesame
  • -embxml gradebook.xml gt signature.xml
  • Key store test.keystore
  • Sign 851ms

18
Examine Signature.xml
  • ltSignature xmlns"http//www.w3.org/2000/09/xmldsi
    g"gt
  • ltSignedInfogt
  • ltCanonicalizationMethod Algorithm"http//www.
    w3.org/TR/2001/REC-xml-c14n-20010315"gtlt/Canonicali
    zationMethodgt
  • ltSignatureMethod Algorithm"http//www.w3.org/
    2000/09/xmldsigrsa-sha1"gtlt/SignatureMethodgt

19
We are signing resource 0
  • ltReference URI"Res0"gt
  • ltTransformsgt
  • ltTransform Algorithm"http//www.w3.
    org/TR/2001/REC-xml-

  • c14n-20010315"gt
  • lt/Transformgt
  • lt/Transformsgt
  • ltDigestMethod
  • Algorithm"http//www.w3.org
    /2000/09/xmldsigsha1"gt
  • lt/DigestMethodgt
  • ltDigestValuegtm6f9xhOc4iEXokD/29V9EsdY3yI
  • lt/DigestValuegt
  • lt/Referencegt

20
  • lt/SignedInfogt
  • ltSignatureValuegt
  • Gll1H/uplOwfaX3j7ST6UqQlc92Hx2nsCdN2KWz32CW0
    D4hH64n32v/InkGux1dYgTya6S4s55iHqZEjDpH2I359H4PAxB
    YYXJj4LUBNxAFxUcDy6xrEUbLnKeutT5pf1DBSmxg9Cp3PO5Rs
    36nVN8GVfnFl1M86WQd19/RsAnA
  • lt/SignatureValuegt

21
  • ltKeyInfogt
  • ltKeyValuegt
  • ltRSAKeyValuegt
  • ltModulusgt
  • 7V5eyhVaw0clED11H6PTPoKQA1VxrLAugU3QxKA0
    hbbUOiavFbqCdc6ZFe9JZFMkS
  • IqdlkhwWwdAIsRyrN4V2DWm1fxyYQf6bdZgCa
    VVgkST1BpQxBTgNKRcS5VbLrXf
  • 4MXb5TbhAeo1Qbr2IjlV10aLbVhUk/gylagk
  • lt/Modulusgt
  • ltExponentgtAQABlt/Exponentgt
  • lt/RSAKeyValuegt
  • lt/KeyValuegt

22
  • ltX509Datagt
  • ltX509IssuerSerialgt
  • ltX509IssuerNamegtCNMike
    McCarthy,OUHeinz
  • School,OCMU,LPgh,STPA,CUS
  • lt/X509IssuerNamegt
  • ltX509SerialNumbergt1049138061
  • lt/X509SerialNumbergt
  • lt/X509IssuerSerialgt
  • ltX509SubjectNamegtCNMike
    McCarthy,OUHeinz
  • School,OCMU,LPgh,STPA,CUS
  • lt/X509SubjectNamegt
  • ltX509Certificategt

23
  • MIICPDCCAaUCBD6Ik40wDQYJKoZIhvcNAQEEBQAwZTELMAkGA1
    UEBhMCVVMxCzAJBgNVBAgTAlBB
  • MQwwCgYDVQQHEwNQZ2gxDDAKBgNVBAoTA0NNVTEVMBMGA1UECx
    MMSGVpbnogU2Nob29sMRYwFAYD
  • VQQDEw1NaWtlIE1jQ2FydGh5MB4XDTAzMDMzMTE5MTQyMVoXDT
    AzMDYyOTE5MTQyMVowZTELMAkG
  • A1UEBhMCVVMxCzAJBgNVBAgTAlBBMQwwCgYDVQQHEwNQZ2gxDD
    AKBgNVBAoTA0NNVTEVMBMGA1UE
  • CxMMSGVpbnogU2Nob29sMRYwFAYDVQQDEw1NaWtlIE1jQ2FydG
    h5MIGfMA0GCSqGSIb3DQEBAQUA
  • A4GNADCBiQKBgQDtXl7KFVrDRyUQPXUfo9MgpADVXGssC6BTd
    DEoDSFttQ6Jq8VuoJ1zpn4V70l
  • kUyRIip2X6SHBbB34AixHKs3hXYNabV/7HJhB/pt1mAJpVWCRJ
    PUGlDEFOA0pFxLlVsutd/gxdvl
  • NuED56jVBuvYiOVXXRottWFSTD7KVqD6QIDAQABMA0GCSqGSI
    b3DQEBBAUAA4GBAMpUaA8Cw8mK
  • Qn408KuV4xrTciEEcTLNniDGnf8d9W1fR4veqhKz8L88864b
    NS5Wih1oEC5k/da23QicpTdXf
  • UyA1c29Zu3cGU4ulUfhFPWv0IgdpI63KQt9QwsuTxWck5dAta2
    KWWTv85IhByHXgoaDlvJ65JjT
  • 87nAPAI3

24
  • lt/X509Certificategt
  • lt/X509Datagt
  • lt/KeyInfogt
  • ltdsigObject xmlns""

  • xmlnsdsig"http//www.w3.org/2000/09/xmldsig"
  • Id"Res0"gt
  • ltGradeBookgt
  • ltStudentgt
  • ltScoregt100lt/Scoregt
  • ltScoregt89lt/Scoregt
  • lt/Studentgt
  • lt/GradeBookgt
  • lt/dsigObjectgt
  • lt/Signaturegt

The resource 0 object
25
Verify the signature
  • D\McCarthy\www\95-804\IBMXMLSecuritySuite\SampleS
    ign2gt
  • java VerifyCUI lt 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 CNMike McCarthy, OUHeinz
    School, OCMU, LPgh,
  • STPA, CUS
  • IssuerDN CNMike McCarthy, OUHeinz
    School, OCMU, LPgh,
  • STPA, CUS
  • Serial 0x3e88938d
  • Time to verify 490 msec
  • Core Validity OK
  • Signature Validity OK

26
Lets change the low grade!
  • ltdsigObject xmlns"" xmlnsdsig"http//www.w3.o
    rg/2000/09/xmldsig" Id"Res0"gt
  • ltGradeBookgt
  • ltStudentgt
  • ltScoregt100lt/Scoregt
  • ltScoregt100lt/Scoregt
  • lt/Studentgt
  • lt/GradeBookgtlt/dsigObjectgt

27
And run verify
  • D\McCarthy\www\95-804\IBMXMLSecuritySuite\SampleS
    ign2gtjava VerifyCUI lt 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 CNMike McCarthy, OUHeinz
    School, OCMU, LPgh, STPA, CUS
  • IssuerDN CNMike McCarthy, OUHeinz
    School, OCMU, LPgh, STPA, CUS
  • Serial 0x3e88938d
  • Time to verify 521 msec
  • Core Validity NG
  • Signature Validity OK
  • 0 "Res0" NG Digest value mismatch
    calculated tfVyHns8wRB6l/HDU2dXZkzf7Q
  • Exception in thread "main" java.lang.RuntimeExcept
    ion Core Validity NG
  • at dsig.VerifyCUI.main(VerifyCUI.java137)

28
Another Example PO.XML
  • lt?xml version"1.0" encoding"UTF-8"?gt
  • ltPurchaseOrder xmlns"urnpurchase-order"gt
  • ltCustomergt
  • ltNamegtRobert Smithlt/Namegt
  • ltCustomerIdgt788335lt/CustomerIdgt
  • lt/Customergt
  • ltItem partNum"C763"gt
  • ltProductIdgt6883-JF3lt/ProductIdgt
  • ltQuantitygt3lt/Quantitygt
  • ltShipDategt2002-09-03lt/ShipDategt
  • ltNamegtThinkPad X20lt/Namegt
  • lt/Itemgt
  • lt/PurchaseOrdergt

29
PO After Signing
  • lt?xml version'1.0' encoding'UTF-8'?gt
  • ltSignedPurchaseOrdergt
  • ltPurchaseOrder id"id0" xmlns"urnpurchase-o
    rder"gt
  • ltCustomergt
  • ltNamegtRobert Smithlt/Namegt
  • ltCustomerIdgt788335lt/CustomerIdgt
  • lt/Customergt
  • ltItem partNum"C763"gt
  • ltProductIdgt6883-JF3lt/ProductIdgt
  • ltQuantitygt3lt/Quantitygt
  • ltShipDategt2002-09-03lt/ShipDategt
  • ltNamegtThinkPad X20lt/Namegt
  • lt/Itemgt
  • lt/PurchaseOrdergt

30
  • ltSignature xmlns"http//www.w3.org/2000/09/xmldsi
    g"gt
  • ltSignedInfogt
  • ltCanonicalizationMethod Algorithm"http//www
    .w3.org/TR/2001/REC-xml-c14n-20010315"/gt
  • ltSignatureMethod Algorithm"http//www.w3.org/
    2000/09/xmldsigrsa-sha1"/gt
  • ltReference URI"id0"gt
  • ltDigestMethod Algorithm"http//www.w3.org/2
    000/09/xmldsigsha1"/gt
  • ltDigestValuegtUfeiscUCL7QkhZtRDLWDPWLpVlAlt/D
    igestValuegt
  • lt/Referencegt
  • lt/SignedInfogt

31
  • ltSignatureValuegt
  • Ptysg8WdHI2mxwryOOt5I9r9qZm/2gNFNOJyH1Wak4nCUe
    gRpe72tWnsigAKZyopmgUSH3TG
  • aGGQF1BTSvk3JUUY/ljrw5FpTpf3hgZBi7GSWf6WtXqZvM
    YGUKIlvR/421MZg7P9XRUyy37
  • ZUzQHtmCYkBorEkEx1J4CYB0G2c
  • lt/SignatureValuegt

32
  • ltKeyInfogt
  • ltX509Datagt
  • ltX509Certificategt
  • MIIDGjCCAoOgAwIBAgICAQAwDQYJKoZIhvcNAQEFBQ
    AwXzELMAkGA1UEBhMCSlAxETAPBgNVBAgT
  • CEthbmFnYXdhMQ8wDQYDVQQHEwZZYW1hdG8xDDAKBg
    NVBAoTA0lCTTEMMAoGA1UECxMDVFJMMRAw
  • DgYDVQQDEwdUZXN0IENBMB4XDTAxMTAwMTA3MTYxMF
    oXDTExMTAwMTA3MTYxMFowUDELMAkGA1UE
  • BhMCSlAxETAPBgNVBAgTCEthbmFnYXdhMQwwCgYDVQ
    QKEwNJQk0xDDAKBgNVBAsTA1RSTDESMBAG
  • A1UEAxMJU2lnbmF0dXJlMIGfMA0GCSqGSIb3DQEBAQ
    UAA4GNADCBiQKBgQCvnFQiPEJnUZnkmzoc
  • MjsseD8ms9HBgasZR0VOAvsby5aajsm9CtB18dDCem
    DXZ2YjBdprXepfF4SLNP5ankfphhr9QXA
  • NJdCKpyF3jPoydckle7E7gI9w3Q4NDa4ryVOuIS2q
    ev6jlE7OVPqiXIDVlCH4u6GbIoJEpJ57yzx
  • dQIDAQABo4HzMIHwMAkGA1UdEwQCMAAwCwYDVR0PBA
    QDAgXgMCwGCWCGSAGGEIBDQQfFh1PcGVu
  • U1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ
    4EFgQUYapFv9MvQ9NNn1Q7zgzqka4XORsw
  • gYgGA1UdIwSBgDBgBR7FuT9bLBj3vVsgAzIeYa4hB
    UZBaFjpGEwXzELMAkGA1UEBhMCSlAxETAP
  • BgNVBAgTCEthbmFnYXdhMQ8wDQYDVQQHEwZZYW1hdG
    8xDDAKBgNVBAoTA0lCTTEMMAoGA1UECxMD
  • VFJMMRAwDgYDVQQDEwdUZXN0IENBggEAMA0GCSqGSI
    b3DQEBBQUAA4GBALFzGDXMzxJvOnCdJCMZ
  • 2NsZdz1wmoYyejB5J6Ch2ygdPeibMnW/CiYKCTWBh
    pEgxEqr1BNlgSVqA6nyvjHsVIvgBfwx37D
  • hJ5hz4azpWu1X22XqyU9fUqoQUtEAdM/MlLekBkprk
    JVb9uJXTFzzvm/3DoEiBkX/BT78YdM8eq0

33
.NET Example
34
Hybrid Encryption
  • The way its 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
  • ltRSAKeyValuegt
  • ltModulusgtz9zv0HMRK44BrjYIQtmKlDkA6WnQCIVOYmOjy/eKh
    FqXJM024JybC/5hOCQoYRRo5iYRopIV4gBZUBSolxgk8jIr38i
    O84lDoSisPl3ikcob/aCuhPe8jSl4zbKpiJrqQE8rSNJ3XDPD
    VIiRoDbSRbn04x210tjYNMbePw0RQklt/Modulusgt
  • ltExponentgtAQABlt/Exponentgt
  • lt/RSAKeyValuegt

37
The RSA Public/Private Key data in XML
  • ltRSAKeyValuegt
  • ltModulusgt
  • z9zv0HMRK44BrjYIQtmKlDkA6WnQCIVOYmOjy/eKhFqX
    JM024JybC/5hOCQoYRRo5iYRopIV4gBZUBSolxgk8jIr38iO84
    lDoSisPl3ikcob/aCuhPe8jSl4zbKpiJrqQE8rSNJ3XDPDVIi
    RoDbSRbn04x210tjYNMbePw0RQk
  • lt/Modulusgt
  • ltExponentgtAQABlt/Exponentgt

38
ltPgt 54xO9DFJ4Mydzqrq8/0mcWInv4pUbJHx1W1TYiybkRs7T
chIq56z1JSgedh SxYvGHfHKzDcdplK2PHC9Aik2w lt/Pgt
ltQgt 5dBTIHj9btkq9Nss0ZC04OyRGjssKJs8Y89MOhs9BB1YN
nk6Ci6PqV8F2P 8FwcSFLXb5II7nuvRTGS5enQ6w lt/Qgt
ltDgt sLBBOZNWGQvQ6eEMDKcWYQBDgiVrrJKEGqZ P6WU13WOT7
rhx2WPFdB3i11Q5ZSPxnK9ss8y wrVBNg0ZcbYYUCg6fYsfy
lKv1Lbpxr9h002syvR jmyywRcD9TfvrVhOe27QYJKlE/QX4S
HSgnTxq 4qkmHdTxZRtoRGGLdZ8XE lt/Dgt lt/RSAKeyValuegt

39
The Encrypted Session Key
  • ltEncryptedKey CarriedKeyName"My 3DES Session
    Key"gt
  • ltEncryptionMethod Algorithm"http//www.w3.org/200
    1/04/xmlencrsa-1_5"/gt
  • ltdsKeyInfogt
  • ltKeyNamegtMy Private Keylt/KeyNamegt
  • lt/dsKeyInfogt

40
ltCipherDatagt ltCipherValuegt
Shy7Nzo/ctBPAhwubFiAYpNNB2CuM4TpCUozP2oQZrEMT03O
EzspgkBaItai8ImBUiSUT1KlPCbawG2edz40ISgJG
Sl4m6ZNm L0//gqs4/7eUyLY0rSFeCnW9hKU/hr0r4
wDJaKiIhS68OTHeBBc GLCyFEPSCQXeqbnvqQBo
lt/CipherValuegt lt/CipherDatagt lt/EncryptedKeygt
41
The Original Invoice
  • ltinvoicegt
  • ltitemsgt
  • ltitemgt
  • ltdescgtDeluxe corncob pipelt/descgt
  • ltunitpricegt14.95lt/unitpricegt
  • ltquantitygt1lt/quantitygt
  • lt/itemgt
  • lt/itemsgt

42
ltcreditinfogt ltcardnumbergt0123456789lt/cardnumb
ergt ltexpirationgt01/06/2005lt/expirationgt
ltlastnamegtFinnlt/lastnamegt ltfirstnamegtHucklebe
rrylt/firstnamegt lt/creditinfogt lt/invoicegt
43
The Encrypted Invoice
  • ltinvoicegt
  • ltitemsgt
  • ltitemgt
  • ltdescgtDeluxe corncob pipelt/descgt
  • ltunitpricegt14.95lt/unitpricegt
  • ltquantitygt1lt/quantitygt
  • lt/itemgt
  • lt/itemsgt

44
ltEncryptedData Type"http//www.w3.org/2001/04/xml
encElement"gt ltdsKeyInfogt ltKeyNamegtMy 3DES
Session Keylt/KeyNamegt lt/dsKeyInfogt ltCipherDatagt
ltCipherValuegt ZS0og/w6JtPj0BDtU4XiAS3ybUsqh4tvp4I
toNO8ZzWUSVl8290HH VG2MfbjPSr00dCftHpaBd8GBgHOUSqG
6wiia3EYy8Bgz7y6NeQ6 zFu9i3J34FyuWETjmkROE/mgRU0
IxQTkcDWQVfUq6TECNafP 9voSvbOGTNbt87Rb0BDcjbAWWLjK
kOT6KOOVwfq60TJxmmkxF onqwVAY2ARlm/yBqvbo2BHux5fvZ
FZBF5jCPZPkuOClYZVXpY3wVB lt/CipherValuegt lt/CipherD
atagt lt/EncryptedDatagt lt/invoicegt
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
The receiver creates RSA keys and places them
in two files one for the receiver and one for
the sender.
class XMLEncryption static void Main(string
args) //create participants Sender sender
new Sender() Receiver receiver new
Receiver() //establish public and private RSA
key information receiver.EstablishXmlRsaParamete
rs( "RsaIncludePrivateParams.xml", "RsaExclu
dePrivateParams.xml")
47
The sender creates an XML document.
//create original XML document to
be encrypted sender.CreateOriginalXmlDocument(
"OriginalInvoice.xml") //create session key
and encrypt via RSA public key byte IV
sender.CreateAndEncryptXmlSessionKey( "RsaExclu
dePrivateParams.xml", "SessionKeyExchange.xml")

And generates a symmetric encryption key that is
encrypted with the public key of the receiver.
E(SK)
48
The sender encrypts sensitive parts of the
document.
//encrypt original
XML document with session key sender.EncryptOrig
inalXmlDocument( "OriginalInvoice.xml", "Rsa
ExcludePrivateParams.xml", "SessionKeyExchange.
xml", // no need "EncryptedInvoice.xml") //
decrypt XML document with session
key receiver.DecryptXmlDocument( "EncryptedIn
voice.xml", "RsaIncludePrivateParams.xml", "
SessionKeyExchange.xml", "DecryptedCreditInfo.x
ml", IV)
The receiver decrypts the session key and is then
able to decrypt the document.
49
class Sender public void CreateOriginalXmlDocum
ent(String originalFilename) //establish the
original XML document XmlDocument xmlDoc new
XmlDocument() xmlDoc.PreserveWhitespace
true xmlDoc.LoadXml( "ltinvoicegt\n" "
ltitemsgt\n" " ltitemgt\n" "
ltdescgtDeluxe corncob pipelt/descgt\n" "
ltunitpricegt14.95lt/unitpricegt\n" "
ltquantitygt1lt/quantitygt\n" " lt/itemgt\n"
" lt/itemsgt\n" " ltcreditinfogt\n"
" ltcardnumbergt0123456789lt/cardnumbergt\n"
" ltexpirationgt01/06/2005lt/expirationgt\n
" " ltlastnamegtFinnlt/lastnamegt\n" "
ltfirstnamegtHuckleberrylt/firstnamegt\n" "
lt/creditinfogt\n" "lt/invoicegt\n")
The sender builds the document the hard way.
This part is sensitive.
50
//write original XML document to
file StreamWriter file new
StreamWriter(originalFilename) file.Write(xmlDo
c.OuterXml) file.Close() //let the user
know what happened Console.WriteLine( "Origin
al XML document written to\n\t"
originalFilename)
Write the hand built XML to a file.
51
The sender creates the session key.
public byte CreateAndEncryptXmlSessionKey( St
ring rsaExcludePrivateParamsFilename, String
keyFilename) //create the session key for
3DES bulk encryption TripleDESCryptoServiceProvi
der tripleDES new TripleDESCryptoServiceProv
ider() //access the IV and Key for sender
encryption IV tripleDES.IV Key
tripleDES.Key //fetch public only RSA
parameters from XML StreamReader fileRsaParams
new StreamReader( rsaExcludePrivateParamsFile
name) String rsaExcludePrivateParamsXML
fileRsaParams.ReadToEnd() fileRsaParams.Clo
se()
Before encrypting the key it needs the public
key of the receiver.
52
//RSA encrypt session key
RSACryptoServiceProvider rsa new
RSACryptoServiceProvider() rsa.FromXmlString(r
saExcludePrivateParamsXML) 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 document to hold it.
53
//add EncryptedKey element to key XML
XmlElement xmlEncryptedKey xmlKeyDoc.CreateEle
ment("EncryptedKey") xmlKeyDoc.AppendChild(x
mlEncryptedKey) XmlAttribute
xmlCarriedKeyName xmlKeyDoc.CreateAttribute("
CarriedKeyName") xmlCarriedKeyName.Value
"My 3DES Session Key" xmlEncryptedKey.Attrib
utes.Append( xmlCarriedKeyName)
So far we have ltEncryptedKey CarriedKeyName"My
3DES Session Key"gt
54
//add the EncryptionMethod element to key XML
XmlElement xmlEncryptionMethod
xmlKeyDoc.CreateElement("EncryptionMethod")
xmlEncryptedKey.AppendChild(xmlEncryptionMetho
d) XmlAttribute xmlAlgorithm
xmlKeyDoc.CreateAttribute("Algorithm")
xmlAlgorithm.Value "http//www.w3.org/2001/04/xm
lencrsa-1_5" xmlEncryptionMethod.Attributes
.Append( xmlAlgorithm)
ltEncryptedKey CarriedKeyName"My 3DES Session
Key"gt ltEncryptionMethod Algorithm
"http//www.w3.org/2001/04/xmlencrsa-1_
5" /gt
55
//add KeyInfo
element to key XML XmlElement xmlKeyInfo
xmlKeyDoc.CreateElement( "ds",
"KeyInfo", "http//www.w3.org/2000/09/xmlds
ig") xmlEncryptedKey.AppendChild(xmlKeyInfo)
//add KeyName element to key XML XmlElement
xmlKeyName xmlKeyDoc.CreateElement("ds",
"KeyName", null) xmlKeyName.InnerText "My
Private Key" xmlKeyInfo.AppendChild(xmlKeyName)

ltdsKeyInfo xmlnsds"http//www.w3.org/2000/09/xm
ldsig"gt ltKeyNamegtMy Private Keylt/KeyNamegt lt/dsKe
yInfogt
56
//add CipherData
element to key XML XmlElement xmlCipherData
xmlKeyDoc.CreateElement("CipherData") xmlEn
cryptedKey.AppendChild(xmlCipherData)
ltCipherDatagt
57
//add CipherValue
element to key XML XmlElement xmlCipherValue
xmlKeyDoc.CreateElement("CipherValue")
xmlCipherValue.InnerText
keyEncryptedString xmlCipherData.AppendChild
(xmlCipherValue)
ltCipherValuegtShy7Nzo/ctBPAhwubFiAYpNNB2CuM4TpC Uoz
P2oQZrEMT03OEzspgkBaItai8ImBUiSUT1KlPCbawG 2edz40I
SgJGSl4m6ZNmL0//gqs4/7eUyLY0rSFeCnW9h KU/hr0r4wD
JaKiIhS68OTHeBBcGLCyFEPSCQXeqbnvq QBo lt/CipherVa
luegt lt/CipherDatagt lt/EncryptedKeygt
58
//save key XML
information xmlKeyDoc.Save(keyFilename) //le
t the user know what happened Console.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 EncryptOriginalXmlDocum
ent( String originalFilename, String
rsaExcludePrivateParamsFilename, String
keyFilename, String encryptedFilename)
Document partially encrypted with session key
Receivers public key
Encrypted symmetric key file name??
Original XML Document
60
Load the document holding sensitive tag
//load XML document to be encrypted XmlDocument
xmlDoc new XmlDocument() xmlDoc.PreserveWhitesp
ace true xmlDoc.Load(originalFilename) //get
creditinfo node plaintext bytes to
encrypt XmlElement xmlCreditinfo
(XmlElement)xmlDoc.SelectSingleNode( "invoic
e/creditinfo") byte creditinfoPlainbytes
Encoding.UTF8.GetBytes(xmlCreditinfo.OuterXml)

Find the tag
Get the bytes and include the tag name.
61
//create 3DES
algorithm object for bulk encryption TripleDESCr
yptoServiceProvider tripleDES new
TripleDESCryptoServiceProvider()
Getting ready for symmetric encryption
62
//establish crypto stream using 3DES
algorithm MemoryStream ms new
MemoryStream() CryptoStream cs new
CryptoStream( ms, tripleDES.CreateEncryptor(
Key, IV), CryptoStreamMode.Write) //write
creditinfo plaintext to crypto stream cs.Write(
creditinfoPlainbytes, 0,
creditinfoPlainbytes.Length) cs.Close()

Use the same Key that we Encrypted before
Encrypt the sensitive tag with the session key.
63
Get the encrypted bytes and convert them to base
64
//get creditinfo
ciphertext from crypto stream byte
creditinfoCipherbytes ms.ToArray() ms.Close()
String creditinfoCiphertext
Convert.ToBase64String( creditinfoCipherby
tes)
64
//create
EncryptedData in XML file XmlElement
xmlEncryptedData xmlDoc.CreateElement("Encry
ptedData") XmlAttribute xmlType
xmlDoc.CreateAttribute("Type") xmlType.Valu
e "http//www.w3.org/2001/04/xmlencElement"
xmlEncryptedData.Attributes.Append(xmlType)
//add KeyInfo element XmlElement xmlKeyInfo
xmlDoc.CreateElement( "ds",
"KeyInfo", "http//www.w3.org/2000/09/xmlds
ig") xmlEncryptedData.AppendChild(xmlKeyInfo)

XML Encryption
65
//add KeyName
element XmlElement xmlKeyName
xmlDoc.CreateElement("ds", "KeyName",null)
xmlKeyName.InnerText "My 3DES Session
Key" xmlKeyInfo.AppendChild(xmlKeyName) //a
dd CipherData element XmlElement xmlCipherData
xmlDoc.CreateElement("CipherData") xmlEnc
ryptedData.AppendChild(xmlCipherData) //add
CipherValue element with encrypted
creditinfo XmlElement xmlCipherValue
xmlDoc.CreateElement("CipherValue") xmlCiph
erValue.InnerText creditinfoCiphertext xmlCip
herData.AppendChild(xmlCipherValue)
66
//replace original
node with the encrypted node xmlCreditinfo.Paren
tNode.ReplaceChild( xmlEncryptedData,
xmlCreditinfo) //save XML to encrypted
file xmlDoc.Save(encryptedFilename) //let
the user know what happened Console.WriteLine(
"Encrypted XML document written to\n\t"
encryptedFilename) //information sender
needs across method calls static byte
IV static byte Key
The encrypted document is built. The receiver
needs to read it
67
What does the receiver need ?
  • The encrypted document
  • The encrypted session key

68
class Receiver public void EstablishXmlRsaPara
meters( String rsaIncludePrivateParamsFilename,
String rsaExcludePrivateParamsFilename) //
create RSA object with new key pair RSACryptoSer
viceProvider rsa new RSACryptoServiceProvide
r() //store public and private RSA key params
in XML StreamWriter fileRsaIncludePrivateParams
new StreamWriter( rsaIncludePrivateParams
Filename) fileRsaIncludePrivateParams.Write(
rsa.ToXmlString(true)) fileRsaIncludePrivatePa
rams.Close()
Executed before anything else
The receiver needs the public and private keys.
69
//store public only
RSA key params in XML StreamWriter
fileRsaExcludePrivateParams new
StreamWriter( rsaExcludePrivateParamsFilename)
fileRsaExcludePrivateParams.Write( rsa.ToXml
String(false)) fileRsaExcludePrivateParams.Clos
e() //let the user know what
happened Console.WriteLine( "RSA parameters
written to\n\t" rsaIncludePrivateParamsFile
name "\n\t" rsaExcludePrivateParamsFilename
)
The sender needs the public keys. Two files
written.
70
public void DecryptXmlDocument( St
ring encryptedFilename, String
rsaIncludePrivateParamsFilename, String
keyFilename, String decryptedFilename, byte
IV) //load encrypted XML
document XmlDocument xmlDoc new
XmlDocument() xmlDoc.PreserveWhitespace
true xmlDoc.Load(encryptedFilename) //get
creditinfo node ciphertext bytes to
decrypt XmlElement xmlEncryptedData
(XmlElement)xmlDoc.SelectSingleNode( "invoi
ce/EncryptedData")
Decrypt get the document and find the encrypted
element
71
XmlElement xmlCipherValue
(XmlElement)xmlEncryptedData.SelectSingleNode(
"CipherData/CipherValue") byte
creditinfoCipherbytes Convert.FromBase64Stri
ng( xmlCipherValue.InnerText) //load
XML key document XmlDocument xmlKeyDoc new
XmlDocument() xmlKeyDoc.PreserveWhitespace
true xmlKeyDoc.Load(keyFilename) //get
encrypted session key bytes XmlElement
xmlKeyCipherValue (XmlElement)xmlKeyDoc.Sele
ctSingleNode( "EncryptedKey/CipherData/CipherVa
lue") byte xmlKeyCipherbytes
Convert.FromBase64String(
xmlKeyCipherValue.InnerText)
Get encrypted bytes
Get the encrypted symmetric key..
..as an array of bytes
72
//Get RSA private key
to decrypt the session key StreamReader
fileRsaParams new StreamReader( rsaIncludePri
vateParamsFilename) String rsaIncludePrivatePa
ramsXML fileRsaParams.ReadToEnd() fileRsa
Params.Close() //RSA decrypt 3DES session
key RSACryptoServiceProvider rsa new
RSACryptoServiceProvider() rsa.FromXmlString(rs
aIncludePrivateParamsXML) byte
keyPlainBytes rsa.Decrypt(xmlKeyCipherbytes,
false) //create 3DES algorithm object for
bulk encryption TripleDESCryptoServiceProvider
tripleDES new TripleDESCryptoServiceProvider(
)
Get the RSA Private key
Decrypt the session key
Prepare to use DES decryption
73
//establish crypto
stream using 3DES algorithm MemoryStream ms
new MemoryStream( creditinfoCipherbytes) Cry
ptoStream cs new CryptoStream( ms, tripleD
ES.CreateDecryptor(keyPlainBytes,
IV), CryptoStreamMode.Read) //read
creditinfo plaintext from crypto stream byte
creditinfoPlainbytes new BytecreditinfoCiph
erbytes.Length cs.Read( creditinfoPlainbyte
s, 0, creditinfoPlainbytes.Length) cs.C
lose() ms.Close() String
creditinfoPlaintext Encoding.UTF8.GetString(
creditinfoPlainbytes)
Operate on the Sensitive data
Now its in the clear
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 file StreamWriter fileplaintext
new StreamWriter(decryptedFilename) filepla
intext.Write(xmlDoc.OuterXml) fileplaintext.Cl
ose() //let the user know what
happened Console.WriteLine( "Decrypted XML
credit info written to\n\t" decryptedFilena
me)
Write a Comment
User Comments (0)
About PowerShow.com