How to Encrypt a PDF and Protect Your Documents

PDF files hold our top secrets. But a person can open it and take our data. So, we must keep our files safe. There are a lot of ways to do that, such as

  • Stop bad access with strong protection

  • Use a password for a secure PDF file

  • Add tools to stop edits

  • We can hide text

  • We can keep our data safe from bad hands

In this blog UniDoc will help you learn how to password protect PDF with UniPDF. So, you can secure a confidential PDF and have peace of mind.

Let us start.

Why You Should Encrypt PDF Files

Here is why I should do it.

1. It stops bad access

A password protected PDF stops a stranger from open access. So, your data stays safe.

It gives strong PDF file security. It also helps protect PDF from unauthorized access.

2. It keeps private data safe

A secure confidential PDF locks your ID papers. It locks the bills. It locks office files. It keeps your life safe.

3. It stops edits

Most bad actors try to change the text in a file. A lock can protect PDF from editing. So, no one can change your data.

4. It stops copy

A lock can prevent copying from PDF. So, your words stay on your own.

5. It follows rules

Some jobs need PDF privacy protection. Some laws also need strong care. A lock helps with that.

Before starting with UniPDF, make sure your system is properly set up. Follow these steps to prepare your environment.

  1. Install Go
  • Download the latest stable version of Go from the official website.

  • Follow the installation guide for your operating system (Windows, macOS, or Linux).

  • To confirm installation, run:

go version

This will display the installed version.

  1. Set Up Your Development Environment
  • Make sure your system PATH includes the Go binary.

  • Create a dedicated workspace folder for UniPDF projects to keep everything organized

  1. Get a UniPDF License Key
  • You’ll need a valid license key to run UniPDF examples without errors.

  • If you don’t have one yet, request a key from the UniDoc website.

1. Password Protect with PDF Editor

A password protect PDF is a lock on the file. A person must type a password before the file opens. It keeps data safe. It makes a secure PDF file. It also helps protect PDF with strong password so people cannot read it. You can do it via Adobe, Go, or any other tool available online.

How to do it

  • Open your file in a PDF tool

  • Pick the protect option. You set the lock here.

  • Add a good key. Set a strong key. Use letters and numbers together

  • Save the file. Now only trusted people can open it

Good side

Easy. Fast. Works nicely for small jobs. Very good for school files or shop bills

Weak side

It stops open access but not deep hacks. Big firms use extra locks too

Here is an example to protect PDF with go and UniPDF library

/*
 * https://github.com/unidoc/unipdf-examples/blob/master/security/pdf_protect.go
 */

package main

import (
	"fmt"
	"os"

	"github.com/unidoc/unipdf/v4/model"

	"github.com/unidoc/unipdf/v4/common/license"
	"github.com/unidoc/unipdf/v4/core/security"
)

func init() {
	// Make sure to load your metered License API key prior to using the library.
	// If you need a key, you can sign up and create a free one at https://cloud.unidoc.io
	err := license.SetMeteredKey(os.Getenv(`UNIDOC_LICENSE_API_KEY`))
	if err != nil {
		panic(err)
	}
}

func main() {
	if len(os.Args) < 5 {
		fmt.Println("Usage: go run pdf_protect.go input.pdf <user-pass> <owner-pass> output.pdf")
		fmt.Println("Sets a user and owner password for the PDF.")
		os.Exit(1)
	}

	inputPath := os.Args[1]
	userPassword := os.Args[2]
	ownerPassword := os.Args[3]
	outputPath := os.Args[4]

	err := protectPdf(inputPath, outputPath, userPassword, ownerPassword)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		os.Exit(1)
	}

	fmt.Printf("Complete, see output file: %s\n", outputPath)
}

func protectPdf(inputPath string, outputPath string, userPassword, ownerPassword string) error {
	permissions := security.PermPrinting | // Allow printing with low quality
		security.PermFullPrintQuality |
		security.PermModify | // Allow modifications.
		security.PermAnnotate | // Allow annotations.
		security.PermFillForms |
		security.PermRotateInsert | // Allow modifying page order, rotating pages etc.
		security.PermExtractGraphics | // Allow extracting graphics.
		security.PermDisabilityExtract // Allow extracting graphics (accessibility)

	encryptOptions := &model.EncryptOptions{
		Permissions: permissions,
	}

	f, err := os.Open(inputPath)
	if err != nil {
		return err
	}
	defer f.Close()

	pdfReader, err := model.NewPdfReader(f)
	if err != nil {
		return err
	}

	isEncrypted, err := pdfReader.IsEncrypted()
	if err != nil {
		return err
	}
	if isEncrypted {
		return fmt.Errorf("The PDF is already locked (need to unlock first)")
	}

	// Generate a PdfWriter instance from existing PdfReader.
	pdfWriter, err := pdfReader.ToWriter(nil)
	if err != nil {
		return err
	}

	// Encrypt document before writing to file.
	err = pdfWriter.Encrypt([]byte(userPassword), []byte(ownerPassword), encryptOptions)
	if err != nil {
		return err
	}

	// Write to file.
	err = pdfWriter.WriteToFile(outputPath)
	return err
}

This code gives a lock. So the file needs a password before opening. It helps lock PDF with password for real use

2. Encrypt PDF Online

Some tools work in a browser. You upload your file. The tool locks it. You download the new file. This gives fast PDF encryption. It is easy for small work. It helps encrypt PDF online if you do not want apps on your PC.

How to do it

  • Go to a trusted web tool

  • Upload your PDF file

  • Set a strong key

  • Download the new file

Now you have secure confidential PDF

Good side

Fast. Easy. No install. Good for quick jobs

Weak side

You must trust the site. Do not use this way for top secret data

This gives PDF protection tools for normal work. It is simple for students or small teams.

3. Make Your PDF Read Only

You can also keep your PDF safe with a read only mode. People can only open the file and see it, but not edit.

There are many ways to do this. You can use your system. You can use Acrobat. You can use other tools.

Way 1: Use Windows to Lock the File

You can lock a PDF on a Windows PC.

Steps

  1. Right click on your PDF

  2. Tap on Properties

  3. Pick Read Only

  4. Press OK

Now the file can open but it can not change.

Way 2: Use a Mac to Lock the File

You can also lock a PDF on a Mac.

Steps

  1. Pick the PDF

  2. Tap File

  3. Tap Get Info

  4. Go to the Sharing and Permissions area

  5. Pick the level you want

  6. Set it to Read Only

Now the file will stop edit. It will only open for view.

Way 3: Use Acrobat or Other PDF Tools

You can also use Acrobat or other PDF apps. These apps let you turn off edit. These apps let you turn off copy. These apps let you set a key for open or view.

Steps

  1. Open the PDF in Acrobat

  2. Go to the Protect area

  3. Pick Restrict Edit

  4. Set a strong key

  5. Save the PDF

Now no one can change the file without the key.

Good Side

It is fast. It is simple. It works for new users. It keeps the file safe.

Weak Side

A person with full file rights can break the read only state. So, this method is safe but not the strongest.

Add a Digital Signature with UniPDF

A digital signature for PDF helps keep your file safe. It shows the file comes from you. It also shows no one changed it. This gives secure PDF file share. It helps your file stay legal in offices and banks. It also adds PDF document security features for high trust.

UniPDF can help you add a digital sign in Go. You use a sign key. You save the file again. Now the file is extra safety.

Simple go code with UniPDF:

/*
 * https://github.com/unidoc/unipdf-examples/blob/master/signatures/pdf_sign_and_encrypt_pdf.go
 */
package main

import (
	"bytes"
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"crypto/x509/pkix"
	"fmt"
	"io/ioutil"
	"log"
	"math/big"
	"os"
	"time"

	"github.com/unidoc/unipdf/v4/common/license"
	"github.com/unidoc/unipdf/v4/core/security"

	"github.com/unidoc/unipdf/v4/annotator"
	"github.com/unidoc/unipdf/v4/core"
	"github.com/unidoc/unipdf/v4/model"
	"github.com/unidoc/unipdf/v4/model/sighandler"
)

func init() {
	//Make sure to load your metered License API key prior to using the library.
	//If you need a key, you can sign up and create a free one at https://cloud.unidoc.io
	err := license.SetMeteredKey(os.Getenv(`UNIDOC_LICENSE_API_KEY`))
	if err != nil {
		panic(err)
	}
}

func main() {
	args := os.Args
	if len(args) < 3 {
		log.Fatalln("Usage: go run pdf_sign_encrypted_pdf INPUT_PDF_PATH OUTPUT_PDF_PATH")
	}

	inputPath := args[1]
	outputPath := args[2]

	// Read the original file.
	f, err := os.Open(inputPath)
	if err != nil {
		log.Fatalf("Fail: %v\n", err)
	}
	defer f.Close()

	pdfReader, err := model.NewPdfReader(f)
	if err != nil {
		log.Fatalf("Fail: %v\n", err)
	}

	password := "password"

	permissions := security.PermPrinting | // Allow printing with low quality
		security.PermFullPrintQuality |
		security.PermModify | // Allow modifications.
		security.PermAnnotate | // Allow annotations.
		security.PermFillForms |
		security.PermRotateInsert | // Allow modifying page order, rotating pages etc.
		security.PermExtractGraphics | // Allow extracting graphics.
		security.PermDisabilityExtract // Allow extracting graphics (accessibility)

	encryptOptions := &model.EncryptOptions{
		Permissions: permissions,
		Algorithm:   model.AES_128bit,
	}

	// Ecnrypt document
	buf, err := encryptDocument(pdfReader, password, encryptOptions)
	if err != nil {
		log.Fatalf("Fail: %v\n", err)
	}

	readerOpts := model.NewReaderOpts()
	readerOpts.Password = password

	// Open reader for the signed document
	pdfReader, err = model.NewPdfReaderWithOpts(bytes.NewReader(buf), readerOpts)
	if err != nil {
		log.Fatalf("Fail: %v\n", err)
	}

	// Create appender.
	pdfAppender, err := model.NewPdfAppenderWithOpts(pdfReader, readerOpts, encryptOptions)
	if err != nil {
		log.Fatalf("Fail: %v\n", err)
	}

	// Add signature
	buf, err = addSignature(pdfAppender, 1)
	if err != nil {
		log.Fatalf("Fail: %v\n", err)
	}

	// Write the resulting file to output.pdf file.
	err = ioutil.WriteFile(outputPath, buf, 0666)
	if err != nil {
		log.Fatalf("Fail: %v\n", err)
	}
	log.Printf("PDF file successfully saved to output path: %s\n", outputPath)

	fmt.Println("Done")
}

func encryptDocument(pdfReader *model.PdfReader, password string, encryptOptions *model.EncryptOptions) ([]byte, error) {
	pdfWriter, err := pdfReader.ToWriter(nil)
	if err != nil {
		return nil, err
	}

	// Encrypt document before writing to file.
	err = pdfWriter.Encrypt([]byte(password), []byte(password), encryptOptions)
	if err != nil {
		return nil, err
	}

	buf := &bytes.Buffer{}
	// Write output PDF file.
	if err = pdfWriter.Write(buf); err != nil {
		return nil, err
	}

	log.Println("PDF file successfully encrypted")

	return buf.Bytes(), nil
}

func addSignature(pdfAppender *model.PdfAppender, pageNum int) ([]byte, error) {
	// Generate key pair.
	priv, cert, err := generateSigKeys()
	if err != nil {
		return nil, err
	}

	// Create signature handler.
	handler, err := sighandler.NewAdobePKCS7Detached(priv, cert)
	if err != nil {
		return nil, err
	}

	// Create signature.
	signature := model.NewPdfSignature(handler)
	signature.SetName("Test Signature Appearance Name")
	signature.SetReason("TestSignatureAppearance Reason")
	signature.SetDate(time.Now(), "")

	// Initialize signature.
	if err := signature.Initialize(); err != nil {
		return nil, err
	}

	opts := annotator.NewSignatureFieldOpts()
	opts.FontSize = 8
	opts.Rect = []float64{float64(50), 250, float64(150), 300}
	opts.TextColor = model.NewPdfColorDeviceRGB(255, 0, 0)

	sigField, err := annotator.NewSignatureField(
		signature,
		[]*annotator.SignatureLine{
			annotator.NewSignatureLine("Name", "John Doe"),
			annotator.NewSignatureLine("Date", "2019.03.14"),
			annotator.NewSignatureLine("Reason", fmt.Sprintf("Test sign")),
			annotator.NewSignatureLine("Location", "London"),
			annotator.NewSignatureLine("DN", "authority2:name2"),
		},
		opts,
	)
	if err != nil {
		return nil, err
	}

	sigField.T = core.MakeString(fmt.Sprintf("New Page Signature"))

	if err = pdfAppender.Sign(pageNum, sigField); err != nil {
		log.Fatalf("Fail: %v\n", err)
	}

	buf := &bytes.Buffer{}
	// Write output PDF file.
	if err = pdfAppender.Write(buf); err != nil {
		return nil, err
	}

	log.Println("PDF file successfully signed")

	return buf.Bytes(), nil
}

func generateSigKeys() (*rsa.PrivateKey, *x509.Certificate, error) {
	var now = time.Now()

	// Generate private key.
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, nil, err
	}

	// Initialize X509 certificate template.
	template := x509.Certificate{
		SerialNumber: big.NewInt(1),
		Subject: pkix.Name{
			CommonName:   "any",
			Organization: []string{"Test Company"},
		},
		NotBefore: now.Add(-time.Hour),
		NotAfter:  now.Add(time.Hour * 24 * 365),

		KeyUsage:              x509.KeyUsageDigitalSignature,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,
	}

	// Generate X509 certificate.
	certData, err := x509.CreateCertificate(rand.Reader, &template, &template, priv.Public(), priv)
	if err != nil {
		return nil, nil, err
	}

	cert, err := x509.ParseCertificate(certData)
	if err != nil {
		return nil, nil, err
	}

	return priv, cert, nil
}

Now your PDF has strong trust. It is safe to share with others

Final Words

Your PDF can hold secret data. So, you must guard it. You can do that with the right lock and tools. UniPDF helps your password protect PDF files in a fast and simple way. It also helps you add strong locks and trust signs. So, no one can open your file without your word. No one can copy your notes or change the file. You stay safe.

Use UniPDF for PDF encryption. Keep your data safe from bad use. You can start now. Try UniPDF and protect your PDF with smart code and strong control.