Sign PDF Using JavaScript and WebCrypto API
The evolution of WebCrypto API and its support in major browsers like Chrome and Firefox has raised the possibility of leveraging it for digital PDF signing. However, the lack of documentation and granular examples poses challenges. While examples exist explaining the signing process, the desired outcome – a signed Base64 PDF string – remains elusive.
Can we sign a PDF using JavaScript and WebCrypto API alone?
Currently, WebCrypto API lacks access to key stores or external cryptographic devices. To accommodate common PDF signing requirements, where the PDF should be protected within server boundaries, sending the entire document to the browser or signing API server is discouraged.
Optimal Approach
An effective solution involves creating a hash of the PDF for signing, sending that hash to the browser, and utilizing JavaScript through a browser extension to access a local keystore (or USB/Smartcard) to generate the signature. The resulting signature (e.g., PKCS7 or CMS container) can be sent back to the server, where it can be injected into the original PDF from which the hash was created.
Signer.Digital Extension for Browser Extensions
To facilitate browser-based signing scenarios, a browser extension called Signer.Digital and an accompanying .NET library are available. The extension works seamlessly with major browsers (Chrome and Firefox), leveraging the Signer.Digital Browser Host to interact with Windows Certificate stores and underlying CSPs to sign hashes.
JavaScript Code Sample
To invoke the signing function from the extension, JavaScript code can be used as follows:
// Calculate Sign for the Hash by Calling function from Extension SignerDigital SignerDigital.signPdfHash(hash, $("#CertThumbPrint").val(), "SHA-256") // or "SHA256" // SignerDigitial.signHashCAdESBr method may be used for producing ICP-Brazil Signature .then( function (signDataResp) { // Send signDataResp to Server }, function (errmsg) { // Send errmsg to server or display the result in browser. } );
Diagram: Digital Signing from Browser
[Image of Digital Signing from Browser]
The above is the detailed content of Can JavaScript and WebCrypto API Alone Sign a PDF?. For more information, please follow other related articles on the PHP Chinese website!