Pesquisar neste blogue

sábado, 28 de maio de 2016

PDF Signing with Smartcards without Applets.

One of my recent projects at work involved developing an alternative  to applets to digital sign PDF files.

After some search i came across open-eid and namely browser-token-signing a true great endeavour from the © Estonian Information System Authority.
You can download their official builds at installer.id.ee. This will install extensions on your browsers that will allow the communication with the smartcards.

https://github.com/open-eid/hwcrypto.js/wiki/ModernAPI

On the client side we will need hwcrypto.js . This lib makes use of Promises caniuse.com which are not available on all browsers however there is a legacy version and other dependencies which can be put in place if you need them.
As stated on their wiki:

    *Support for IE8-IE10 requires a Promises polyfill; IE8 and IE9 also require TypedArray polyfill. Complimentary code is bundled into hwcrypto-legacy.js:

        https://github.com/inexorabletash/polyfill (license: Public Domain / MIT)
        https://github.com/getify/native-promise-only/ (license: MIT)

    Distribution and installation of the necessary platform components is out of scope of this project.


Let's take a look at their example code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// NB! This sample uses the legacy `hex` property!
window.hwcrypto.getCertificate({lang: 'en'}).then(function(certificate) {
   // Do something with the certificate, like prepare the hash to be signed
   var hash = calculateSHA256SignatureHashAsHexForCertificate(certificate.hex);
   // Now sign the hash
   window.hwcrypto.sign(certificate,
 {type: 'SHA-256', hex: hash}, {lang: 'en'}).then(function(signature) {
      // Do something with the signature
      storeSignature(signature.hex);
   }, function(error) {
      // Handle the error. `error.message` is one of the described error mnemonics
      console.log("Signing failed: " + error.message);
   });
});



 As our framework is Java based, to handle the PDF the itextpdf lib was used - itextpdf 5.5.9. I would like to state that with in some work / adaptation pdfsign.js may become the best way to implement such a system. 
To anyone implementing such a system i would like to leave the following notes:

  • If you use some objects to handle the PDF from the server side make sure they are the same all along the process. If not the PDF will still be signed but you may be faced with the "The document has been altered or corrupted since the signature was applied" error.
  • As Promises are  asynchronous take extra care when using it Ajax.

Taking the above into consideration just take a look at Bruno's amazing work/documentation itext-action-second-edition chapter-12  to proceed with the signature.