Sign with Generated Private & Public Key Pair
This guide explains the process of digitally signing a PDF file using a generated private/public key pair.
Sample Input
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:
git clone https://github.com/unidoc/unipdf-examples.git
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.
Linux/Mac
export UNIDOC_LICENSE_API_KEY=PUT_YOUR_API_KEY_HERE
Windows
set UNIDOC_LICENSE_API_KEY=PUT_YOUR_API_KEY_HERE
The next section will explain the example code.
How it works
The import
section imports UniPDF packages and other necessary libraries. The init
function in lines 27-34
, is used to authenticate library request by setting the metered license key form the system environment.
The main
function which is defined in lines 40-116
, does the signing process by generating private/public key pair. Lines 41-47
parse the input path and output path from the command line arguments. The private and public keys are generated in line 50
using generateKeys()
. Then in line 68
a new PdfAppender
is created using model.NewPdfAppender(reader)
.
A signature handler is created in line 74
. Using this handler a model.PdfSignature
object is created and initialized using the following code:
signature := model.NewPdfSignature(handler)
signature.SetName("Test Self Signed PDF")
signature.SetReason("TestSelfSignedPDF")
signature.SetDate(now, "")
if err := signature.Initialize(); err != nil {
log.Fatal("Fail: %v\n", err)
}
In lines 90-103
, a signature field and appearance is created from the handler using the annotator
package of UniPDF. Then the document is signed using appender.Sign(1, field)
in line 105
. Finally, the document is written to a file using appender.WriteToFile(outputPath)
.
The generateKeys()
function returns private and public key pair. It uses the rsa.GenerateKey
and x509.CreateCertificate
functions to generate this key pair.
Run the code
Run the code using the following command:
go run pdf_sign_generate_keys.go <INPUT_PDF_PATH> <OUTPUT_PDF_PATH>