Exploring XML Encryption, Part 2

Implement an XML Encryption engine

In this second installment, Bilal Siddiqui examines the usage model of XML Encryption with the help of a use case scenario. He presents a simple demo application, explaining how it uses the XML Encryption implementation. He then continues with his last implementation of XML Encryption and makes use of JCA/JCE classes to support cryptography. Finally, he briefly discusses the applications of XML Encryption in SOAP-based Web services.


Bilal Siddiqui, CEO, WAP Monster

XML consultant Bilal Siddiqui received a degree in Electronics Engineering from the University of Engineering and Technology, Lahore, Pakistan in 1995. He then began designing software solutions for industrial control systems. Later he turned to XML and used his experience programming in C++ to build Web- and WAP-based XML processing tools, server-side parsing solutions, and service applications. You can contact him at wap_monster@yahoo.com.

01 August 2002

Also available in Japanese Vietnamese

In Part 1 of this series, I gave an introduction to XML Encryption and its underlying syntax and processing. I examined the different tags and their respective use in XML encryption with a simple example of secure exchange of structured data, proposed a Java API for XML Encryption based on DOM, and gave a brief overview of cryptography in Java (JCA/JCE).

I start my discussion in this part with an information exchange scenario, which demonstrates the use of XML encryption.

Information exchange scenario

Consider the process of information exchange between two enterprises. One is an online books-seller and the other is a publisher. When the books-seller wants to purchase books, it submits a purchase order to the publisher. At the publisher's end, the sales department receives this order, processes it, and forwards it to the accounts department. The two enterprises exchange information in the form of XML documents. Since some portion of the document needs to be secure and the rest can be sent insecurely, XML encryption is the natural approach for applying security to distinct portions of the document.

According to the books-seller's security policy, the payment information will only be revealed to the accounts department. The sales department will need to extract only the name of the book, its item ID and the quantity ordered; because this is insensitive information it can remain insecure. The accounts department will need to decrypt the payment information in the purchase order using a pre-exchanged secret key. (Note that XML Encryption is only about encryption and decryption of structured information and does not dictate any particular method of key exchange.) Mapping this policy, XML Encryption facilitates the concealment of payment information in the sales department and its disclosure in the accounts department.

Document-based security

At this point, it may be useful to ponder a bit on the concept of document-based security. With this security architecture, you can impose security at the document level. The context of a secure session is effectively preserved within the secure document. All the information that an authorized party may need to decrypt the document is available inside the document. A logical secure session is created that is flexible, has a long life, and allows numerous parties to be part of the same secure session. An upcoming protocol for Web services, the Business Transaction Protocol (BTP -- see Resources), relies on the same concept of preserving the context of a session within a transaction document; this prolongs the life of a transaction and enhances its flexibility.

The demo application

To fulfill the requirements of the secure data exchange scenario between the publisher and the books-seller described above, I have created a demo application class called demoXmlEncApp (see Listing 1). This class uses the XML Encryption sample implementation class XmlEncryption (see Listing 2).

What the demo application does

The main method of the demoXmlEncApp class first executes the processing at the books-seller's end by calling the simulateBookSellersEnd method, which reads the purchase order XML file, Order.xml (see Listing 3), and encrypts the sensitive information therein through one of the three encryption methods (i.e. complete XML file encryption, element encryption, or element content encryption) specified in XML Encryption. It then saves the XML-encrypted file to disk, as well as the key used for encryption.

Listing 3. Order.xml
<?xml version="1.0"?>
<!-- This Listing provides the sample XML File that will be encrypted. -->
		<BookName>Soccer For Dummies</BookName>

Since file exchange and key exchange protocols are not a concern here, I therefore assume that they are made available to the publisher through any suitable method (for example, the XML-encrypted file and secret key are exchanged through HTTP and some public key encryption algorithm, respectively). The main method then assumes the role of the publisher by calling the simulatePublishersEnd method, which extracts the information needed by the sales department, and displays the received XML file on the console. Further, it decrypts the payment information for the accounts department and displays it on the console.

The simulateBookSellersEnd function in the demoXmlEncApp class first instantiates an XmlEncryption object and calls various setter methods of XmlEncryption to set the following attributes:

  • clearDoc: The DOM object form of the XML file (see Listing 3) to be encrypted
  • encKey: A key used for encryption
  • algoName: Name of the encryption algorithm
  • keyName: Name of the encryption key; this becomes the value of the child text node of the KeyName element during XML encryption as explained in part 1
  • encId: The name given to the EncryptedData tag which is unique in the document

The simulateBookSellersEnd method of demoXmlEncApp class calls the different methods of the XML Encryption engine (XmlEncryption class) depending upon the command line arguments passed while invoking the application. Let's see what happens inside the XmlEncryption class, which is the main XML Encryption processing engine.

XML Encryption implementation details

I already introduced a portion of the proposed XML encryption API in Part 1. Recall that I had a method named encryptCompleteXmlFile in the class XmlEncryption (see Listing 11 of part 1) for encrypting a complete XML file. In addition to the encryptCompleteXmlFile method, I have now added the following two methods to service the encryption requirements of different types of data (encryption granularity):

  • encryptElementOfXmlFile for encrypting a particular element in the XML file
  • encryptElementContentOfXmlFile for encrypting the content of a particular element in the XML file

The books-seller can secure the sensitive information in the purchase order by employing any of the following three XML encryption methods of the XmlEncryption class:

  1. Encrypt a complete XML file
  2. Encrypt an element in an XML file
  3. Encrypt an element's content in an XML file

1. Encrypt a complete XML file with XML Encryption

The books-seller can encrypt the entire Order.xml file to produce an XML-encrypted file, which can then be sent to the publisher's sales department. Although this provides relevant security through the end-to-end communication link, the books-seller's security policy is violated. This policy requires concealing the payment information in the sales department and revealing it in the accounts department. In this case, the whole XML document is decrypted by the sales department and the payment information is disclosed. Therefore this approach does not seem suitable, although it can be practical if you use super encryption (discussed later in this article).

If the books-seller decides to encrypt the entire Order.xml file, the simulateBookSellersEnd function in the class demoXmlEncApp generates a call to the public method encryptCompleteXmlFile of the class XmlEncryption.

This method first calls the getString private method to serialize the XML file to be encrypted into string form. It then calls the encryption method getEncryptedData, which returns a Base 64 encoded cipher text string. The cipher text string is then passed to the getCipherDataDoc private method. This method creates and returns the CipherData tag with the child CipherValue tag, which holds the Base 64 encoded cipher text string. Similarly the EncryptionMethod and ds:KeyInfo tags are created. These three tags -- namely CipherData (which carries its child CipherValue tag), EncryptionMethod, and ds:KeyInfo -- are subsequently added as child tags of the EncryptedData tag. The EncryptedData tag is actually loaded into a DOM document object, encDataObj, which is serialized and returned to the simulateBookSellersEnd method.

2. Encrypt an element in an XML file with XML Encryption

The books-seller can encrypt the payment information portion of the XML file with the accounts department's secret key, and keep the rest of the file content unencrypted for the sales department to view. This processing can be performed by encrypting the Payment element in the Order.xml file. The credit card information becomes secure as it resides in the child nodes of the encrypted Payment element. Since the security requirement dictates that the means of payment (such as credit card or bank check) must be hidden from unauthorized viewers, encrypting the Payment element pays off.

In this case, the simulateBookSellersEnd function in the class demoXmlEncApp generates a call to the public method encryptElementOfXmlFile of the class XmlEncryption. The private method getElement returns the element node which is then serialized and encrypted to produce the CipherData tag. The EncryptedData tag creation process is the same as before, except that this method replaces the Payment element in clearDoc with the EncryptedData element by making a call to the private method replaceElement. After the replacement has taken place, clearDoc is serialized and returned.

3. Encrypt an element's content in an XML file with XML Encryption

The third encryption option the books-seller can exercise is to encrypt only the credit card number in Order.xml. The element content encryption method is invoked, which encrypts only the textual content of the CardNo element. This raises an important question: Why do you need to come up with content encryption when the same can be accomplished using element encryption? The use of either method depends on the security policy for the document; if there is a specific need to disclose the name of the element or its attributes, while keeping its content secure, content encryption comes in handy.

If the books-seller wants to hide the credit card number only, the textual content of the element CardNo in Order.xml is encrypted. The simulateBookSellersEnd method calls the public method encryptElementContentOfXmlFile, which differs from the encryptElementOfXmlFile method only in the sense that it operates on the element's content and not on the element itself.

Using XML Encryption to decrypt an XML-encrypted file

When the publisher's end receives an XML-encrypted file, it will need decryption. For all three encryption methods described, the method for decryption is getDecryptedData. The simulateBookSellersEnd method in demoXmlEncApp serializes the XML-encrypted file into a text string and passes it to the getDecryptedData method for decryption.

The getDecryptedData method identifies the EncryptedData tags and extracts the Base 64 encoded cipher value. All the information necessary for decryption is present within the XML Encryption tags: the name of the encryption algorithm, the type of data that was encrypted, and the name of the encryption key.

Note: The XML Encryption specification does not dictate that all this information should be present within the XML Encryption tags. The presence of these attributes is optional. The application may supply this information through some other means, but the demo application and sample XML Encryption implementation assume the presence of all this information within the XML Encryption tags.

The getDecryptedData method now generates a decryption key from the key and the algorithm names. It then passes the extracted Base 64 encoded cipher value, the decryption key, and the algorithm name to a method named Decrypt (examined in Cryptography).

The Decrypt method returns the decoded and decrypted data as a text string. This text string is manipulated in accordance with the type attribute of the EncryptionData element which may be any one of the following:

  • A complete XML file that is saved to disk as a new XML file
  • An element that replaces the EncryptedData tag to result in the original XML file
  • The content of an element, which replaces the EncryptedData tag to result in the original XML file

Super encryption

When you use super encryption, you can encrypt just the payment information with the accounts department's secret key to produce an element-encrypted XML file. This resultant file is then completely encrypted using the sales department's secret key, thus resulting in a super-encrypted XML file.

Here I must point out that, with the XML Encryption specification, you can re-encrypt an XML-encrypted file which results in a super-encrypted XML file. But, you cannot encrypt a particular child of the EncryptedData or EncryptedKey elements using XML encryption. In other words, an EncryptedData element cannot be the parent or child of another EncryptedData element.

According to the XML Encryption specification, you can also encrypt arbitrary data (for example, a .jpg image or practically anything on the Web). This is nearly identical to the encryption of a complete XML file; the only difference is the value of the type attribute for the EncryptedData element (see Resources).

IANA values

In Part 1 of this series, I used Internet Assigned Numbers Authority (IANA) type definitions as the value of the Type attribute in the EncryptedData tag. Part 1 was based on the XML Encryption W3C Working Draft dated 18 October 2001. Recently, XML Encryption has become a W3C Candidate Recommendation, which no longer uses IANA values (see Resources).


The XML Encryption specification lists a number of required and optional cryptographic algorithms including:

  • Block encryption
  • Stream encryption
  • Key transfer
  • Key agreement
  • Symmetric key wrap
  • Message digest
  • Message authentication

The Base 64 encoding algorithm (see Resources) is also required. Every cipher must be Base 64 encoded before it can be inserted into an XML document. In this demonstration, I use the TripleDES block encryption algorithm of the SunJCE cryptography provider. The mode of encryption is CBC (Cipher Block Chaining) with 8-byte block size.

The XmlEncryption class employs JCA/JCE cryptography, implemented by following methods:

  • getEncryptedData: This method accepts a text string and encrypts it using the TripleDES algorithm. For symmetric encryption (see Resources), you need an encryption key in addition to the clear data being encrypted. This key is available as a private attribute, encKey, of the class XmlEncryption. The input text string is converted into an array of bytes and is padded. I use a block cipher algorithm for encryption that requires the clear data bytes to be in blocks of 8 bytes, so I pad the last incomplete block with some characters. The sample implementation uses a blank space (" ") as the character for padding.

    Next I create a Cipher class object and initiate it in encryption mode. I then extract the initialization vector (IV) into a byte array, block encrypt the clear data, and prefix the IV bytes to the encrypted data bytes. When I use the method getBase64Encoded of the class XmlEncryption, the resultant byte array is then transformed into a Base 64 encoded string and is subsequently returned.

  • Decrypt: This method is essentially the opposite of the getEncryptedData method. It accepts a Base 64 encoded cipher byte array, and decodes and decrypts it to return the clear data string. The IV is then separated from the actual cipher byte array. A Cipher class object is created and initiated in the decryption mode. The cipher byte array is then decrypted, and the decrypted byte array is returned as a text string.

I have provided support for the TripleDES block cipher algorithm only for demonstration. With a few modifications, you can also use other algorithms such as AES.

This simple implementation demonstrates how XML Encryption can be a viable security framework for larger and more complex business applications.

XML Encryption and SOAP

Simple Object Access Protocol, or SOAP (see Resources), is a lightweight XML-based protocol for data exchange. It facilitates the transfer of data resulting from remote procedure calls and responses. It is designed for use in distributed and remote applications, and is a primary component of Web services. SOAP provides an envelope for containing a message and its processing information. Since the content of this envelope can be confidential, security is an issue that you must address. XML Encryption provides a seamless solution to this problem.

SOAP itself is XML, which gives you the freedom to handle encryption issues in any suitable fashion using XML Encryption. For example, you may decide to encrypt the entire SOAP body or a part of the body. However, XML-SEC is a W3C effort aimed at standardizing the ways of implementing security in SOAP-based Web services. At the moment, it does not include XML Encryption; I expect XML Encryption or a similar encryption methodology to be part of it in the future.


In Part 1, I introduced XML Encryption and discussed its use for achieving secure data exchange. I elaborated on the use of different XML Encryption tags and proposed a Java API for XML Encryption based on DOM.

Here in Part 2, I have examined a typical data interchange scenario where you can employ XML encryption concepts. I also demonstrated the various types of XML encryption: encrypting a complete XML file, an element of an XML file, or the contents of an XML element. I also discussed decryption, super encryption, and the application of XML encryption concepts in SOAP-based Web services.


Code samplex-encrypt2/x-encrypt2_src.zip---



developerWorks: Sign in

Required fields are indicated with an asterisk (*).

Need an IBM ID?
Forgot your IBM ID?

Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.


All information submitted is secure.

Dig deeper into XML on developerWorks

Zone=XML, Web development
ArticleTitle=Exploring XML Encryption, Part 2