Is there an easier way to sign an XML document in Java?

Rob Hruska picture Rob Hruska · Jan 12, 2010 · Viewed 21.2k times · Source

I'm trying to digitally sign an XML document using Java. I've got an implementation working with some references I've found that use various implementations in the javax.xml.crypto.dsig package.

However, my current implementation is like many of the examples I've looked at - it's rather verbose and involves using no less than 23 different API classes from the java.xml.crypto.dsig, javax.xml.transform, and java.security packages, among others. It feels like I've entered factory factory factory land, and it took me several hours just to figure out what was going on.

My question is, is there an easier way to do this? If I've got public/private key files and I want to add a <Signature/> to an XML document, is there a library out there that just lets me call something like:

OutputStream signFile(InputStream xmlFile, File privateKey)

...without all of the XMLSignatureFactory/CanonicalizationMethod/DOMSignContext craziness?

I'm not very well-versed in cryptography, and the Java-provided API seems rather daunting for developers like myself trying to become familiar with digital signing. If all of this is necessary or there's currently no friendlier API out there, that's fine and I'm willing to accept that as an answer. I'd just like to know if I'm unnecessarily taking the hard road here.

Answer

Pascal Thivent picture Pascal Thivent · Jan 12, 2010

Have look at Apache XML Security. To use the package to generate and verify a signature, checkout the samples in src_samples/org/apache/xml/security/samples/signature/.