How to Encrypt and Password Protect a PDF using Go

Cloudmersive
2 min readNov 21, 2022

Reliable document security is one of the chief advantages of PDF format. Encryption and password protection features make it possible to keep viewership of a document static between a trusted group of peers, eliminating the risk of unwanted parties appending or revising the document. With our free-to-use PDF Encryption & Password Protection API, you can programmatically set custom permissions for dozens of PDF documents (one API call per document) in a one-step process that involves setting a user password, owner password, and encryption key length (values include 128-bit RC4 encryption and 256-bit AES encryption; the latter is the default setting).

Taking advantage of this API is easy; all you need to do is copy & paste the complementary Go code examples provided below and register a free account on our website to get a free-tier Cloudmersive API key (this key will yield a limit of 800 API calls per month & no additional commitments).

To use this API, include the below code examples in your file and fill the required header fields as directed by the code comments:

package main

import (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
)

func main() {

url := "https://api.cloudmersive.com/convert/edit/pdf/encrypt"
method := "POST"

payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
file, errFile1 := os.Open("/path/to/file")
defer file.Close()
part1,
errFile1 := writer.CreateFormFile("inputFile",filepath.Base("/path/to/file"))
_, errFile1 = io.Copy(part1, file)
if errFile1 != nil {
fmt.Println(errFile1)
return
}
err := writer.Close()
if err != nil {
fmt.Println(err)
return
}


client := &http.Client {
}
req, err := http.NewRequest(method, url, payload)

if err != nil {
fmt.Println(err)
return
}
req.Header.Add("userPassword", "<string>")
req.Header.Add("ownerPassword", "<string>")
req.Header.Add("encryptionKeyLength", "<string>")
req.Header.Add("Content-Type", "multipart/form-data")
req.Header.Add("Apikey", "YOUR-API-KEY-HERE")

req.Header.Set("Content-Type", writer.FormDataContentType())
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()

body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(body))
}

Simple as that — you’re all done.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.