Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[UP-14] Add new examples for the DocMDP #168

Merged
merged 4 commits into from
Feb 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 2 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,14 @@ require (
github.com/pkg/errors v0.9.1 // indirect
github.com/sirupsen/logrus v1.8.1 // indirect
github.com/trimmer-io/go-xmp v1.0.0
github.com/unidoc/unipdf/v3 v3.31.0
github.com/unidoc/unipdf/v3 v3.32.0
github.com/wcharczuk/go-chart/v2 v2.1.0
golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b
golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb // indirect
golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7 // indirect
golang.org/x/text v0.3.6
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
gopkg.in/gographics/imagick.v2 v2.6.0
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
)

go 1.13
go 1.13
8 changes: 6 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,15 @@ github.com/thales-e-security/pool v0.0.2 h1:RAPs4q2EbWsTit6tpzuvTFlgFRJ3S8Evf5gt
github.com/thales-e-security/pool v0.0.2/go.mod h1:qtpMm2+thHtqhLzTwgDBj/OuNnMpupY8mv0Phz0gjhU=
github.com/trimmer-io/go-xmp v1.0.0 h1:zY8bolSga5kOjBAaHS6hrdxLgEoYuT875xTy0QDwZWs=
github.com/trimmer-io/go-xmp v1.0.0/go.mod h1:Aaptr9sp1lLv7UnCAdQ+gSHZyY2miYaKmcNVj7HRBwA=
github.com/unidoc/freetype v0.0.0-20220130190903-3efbeefd0c90 h1:Rk4easgDQslR3DK7vwtl6jYMZTF3JqZ3ceUdyT6a3UM=
github.com/unidoc/freetype v0.0.0-20220130190903-3efbeefd0c90/go.mod h1:mJ/Q7JnqEoWtajJVrV6S1InbRv0K/fJerPB5SQs32KI=
github.com/unidoc/pkcs7 v0.0.0-20200411230602-d883fd70d1df/go.mod h1:UEzOZUEpJfDpywVJMUT8QiugqEZC29pDq7kdIZhWCr8=
github.com/unidoc/pkcs7 v0.1.0 h1:9bQfbWMYsIfUP8PyhTcBudOsvbLpNH0MBv4U0P/jDTE=
github.com/unidoc/pkcs7 v0.1.0/go.mod h1:UEzOZUEpJfDpywVJMUT8QiugqEZC29pDq7kdIZhWCr8=
github.com/unidoc/timestamp v0.0.0-20200412005513-91597fd3793a h1:RLtvUhe4DsUDl66m7MJ8OqBjq8jpWBXPK6/RKtqeTkc=
github.com/unidoc/timestamp v0.0.0-20200412005513-91597fd3793a/go.mod h1:j+qMWZVpZFTvDey3zxUkSgPJZEX33tDgU/QIA0IzCUw=
github.com/unidoc/unipdf/v3 v3.32.0 h1:GpQAHDFpQJatXf/iH6ryP1J0GnwPyXhIFuIS219cg1o=
github.com/unidoc/unipdf/v3 v3.32.0/go.mod h1:OUIt+FTxVqRJl3OFuqiPTPaxPwoYUjkmqPiRRh/SfLo=
github.com/unidoc/unitype v0.2.1 h1:x0jMn7pB/tNrjEVjy3Ukpxo++HOBQaTCXcTYFA6BH3w=
github.com/unidoc/unitype v0.2.1/go.mod h1:mafyug7zYmDOusqa7G0dJV45qp4b6TDAN+pHN7ZUIBU=
github.com/wcharczuk/go-chart/v2 v2.1.0 h1:tY2slqVQ6bN+yHSnDYwZebLQFkphK4WNrVwnt7CJZ2I=
Expand All @@ -69,8 +73,8 @@ golang.org/x/crypto v0.0.0-20201002170205-7f63de1d35b0/go.mod h1:LzIPMQfyMNhhGPh
golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b h1:7mWr3k41Qtv8XlltBkDkl8LoP3mpSgBW8BUoxtEdbXg=
golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
golang.org/x/image v0.0.0-20200927104501-e162460cd6b5/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb h1:fqpd0EBDzlHRCjiphRR5Zo/RSWWQlWv34418dnEixWk=
golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.0.0-20211028202545-6944b10bf410 h1:hTftEOvwiOq2+O8k2D5/Q7COC7k5Qcrgc2TFURJYnvQ=
golang.org/x/image v0.0.0-20211028202545-6944b10bf410/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
Expand Down
179 changes: 179 additions & 0 deletions signatures/pdf_sign_docmdp.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
/*
* This example showcases how to sign a PDF document with the DocMDP restriction.
* The file is signed using a private/public key pair.
*
* $ ./pdf_sign_docmdp <INPUT_PDF_PATH> <OUTPUT_PDF_PATH>
*/
package main

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

"github.com/unidoc/unipdf/v3/annotator"
"github.com/unidoc/unipdf/v3/common/license"
"github.com/unidoc/unipdf/v3/core"
"github.com/unidoc/unipdf/v3/model"
"github.com/unidoc/unipdf/v3/model/mdp"
"github.com/unidoc/unipdf/v3/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_docmdp 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)
}

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

// Add signature and write it to output.pdf file.
err = addSignature(pdfReader, totalPage, outputPath)
if err != nil {
log.Fatalf("Fail: %v\n", err)
}

fmt.Println("Done")
}

func addSignature(reader *model.PdfReader, pageNum int, outputPath string) error {
// Create appender.
appender, err := model.NewPdfAppender(reader)
if err != nil {
return err
}

// Generate key pair.
priv, cert, err := generateSigKeys()
if err != nil {
return err
}

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

handler, err := sighandler.NewDocMDPHandler(inner_handler, mdp.FillForms)
if err != nil {
return 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 err
}

opts := annotator.NewSignatureFieldOpts()
opts.FontSize = 8
opts.Rect = []float64{250, 250, 325, 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", "No reason"),
annotator.NewSignatureLine("Location", "London"),
annotator.NewSignatureLine("DN", "authority2:name2"),
},
opts,
)
if err != nil {
return err
}

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

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

// Write output PDF file.
if err = appender.WriteToFile(outputPath); err != nil {
return err
}

log.Printf("PDF file successfully signed. Output path: %s\n", outputPath)

return 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
}