Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create checksum for an XML file in Java

Tags:

java

xml

checksum

I need to create a checksum for an XML file in Java. The basic requirements are:

  1. The order of elements matters;
  2. The name-value pair of attributes is important, but the order of attributes is NOT;
  3. Ignore all white spaces and comments

Anyone can provide any hint or sample code?

Thanks, Mark

like image 620
awatto Avatar asked Dec 06 '25 09:12

awatto


2 Answers

You can make use of the Java Digital XML Signature APIs:

Introduction to the Java Digital XML Signature APIs

like image 57
Dirk Vollmar Avatar answered Dec 08 '25 21:12

Dirk Vollmar


Method 1: Use XSLT to normalize the document.

Essentially you would use XSLT to normalize XML documents so that equivalent documents distill down into the same document. The transformation would:

  1. Maintain element order
  2. Order the attributes of each element (e.g. alphabetize based on the attribute name)
  3. Strip the whitespace and comments

You would then checksum the normalized version of the document.

Some useful references:

  • XSLT Tutorial - https://stackoverflow.com/questions/1858345/xsltwhich-is-the-best-tutorial-you-would-like-to-recommend
  • Identity transformation as a starting point - XSL That Returns the XML unchanged
  • Sort attributes - Using XSL to sort attributes
  • normalize-space() - how to get the normalize-space() xpath function to work?

Method 2. Use a DOM parser

  1. Use a DOM parser to produce a DOM tree
  2. Normalize the DOM tree according to your rules
  3. Traverse the tree and feed the XML items to a checksum calculator

Method 3. Use a SAX or StAX parser

If you don't like the intermediate step of producing a normalized document or DOM tree, you could use SAX or StAX to parse the XML to maintain/order/strip like above on the fly and feed each element/content/attribute/value/etc to a checksum calculator.

like image 37
Bert F Avatar answered Dec 08 '25 23:12

Bert F



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!