Sign with HSM via PKCS11

This guide discusses the process of digitally signing a PDF file using HSM via PKCS11 with UniPDF.

Before you begin

You should get your API key from your UniCloud account.

If this is your first time using UniPDF SDK, follow this guide to set up a local development environment.

Project setup

Clone the project repository

In your terminal, clone examples repository using the following command: It contains the Go code we will be using for this guide.

git clone

Then navigate to the signatures folder in the unipdf-examples directory.

cd unipdf-examples/signatures

Configure environment variables

Configure your license key using the following command: Replace the UNIDOC_LICENSE_API_KEY with your API credentials from your UniCloud account.





How it works

In the above example code, the import section imports the necessary UniPDF packages and other Go libraries. The init function defined in lines 37-44, loads the metered license key from the system environment to authenticate your library request by setting the license using license.SetMeteredKey(os.Getenv(`UNIDOC_LICENSE_API_KEY`)).

The main function which is defined in lines 55-129, is used to generate a certificate and sign the document. In this function, lines 59-63 check the length of the command line arguments. In line 65, the action argument is obtained using action := args[1]. The switch case in lines 66-80 handles different values of the action argument. In lines 82-84 the tokenLabel, tokenPin and keyPairLabel are set from the rest of the command line arguments. If the type of action is add, then the addKeyPair(ctx, keypairLabel) function is used to add a new public/private key pair. If it is sign, the getKeyPair(ctx, keypairLabel) is used to get the signer. Then generateCertificate(signer) is used to get the certificate using the signer. Then in line 123 the document is signed in and written to output file.

The initPKCS11Session function initializes a PKCS11 store and creates a new session. The getKeyPair function gets the crypto11.Signer object. In line 149-156, the addKeyPair function is defined. This function is used to add a new public/private key pair with the specified label. The generateCertificate function in lines 159-182, is used to generate a certificate using the signer provided in the parameters.

The sign function defined in lines 186-255, is used to sign the specified input PDF file using an adobeX509RSASHA1 signature handler and saves the result at the destination specified by the outputPath parameter.

Run the code

Use the following commands to run the code:

To create a key pair:

pdf_sign_hsm_pkcs11_cgo.go add test <PIN> <keypair_label>

To sign a PDF:

pdf_sign_hsm_pkcs11_cgo.go sign test <PIN> <keypair_label> input.pdf input_signed.pdf

Got any Questions?

We're here to help you.