Skip to content

Instantly share code, notes, and snippets.

@matiaskorhonen
Last active May 25, 2023 10:58
Show Gist options
  • Save matiaskorhonen/223bd527279cf49bed1e to your computer and use it in GitHub Desktop.
Save matiaskorhonen/223bd527279cf49bed1e to your computer and use it in GitHub Desktop.
Quick and dirty PDF signing in Ruby (using Origami)
#!/usr/bin/env ruby
require "openssl"
require "time"
begin
require "origami"
rescue LoadError
abort "origami not installed: gem install origami"
end
include Origami
CERT_FILE = "certificate.crt"
KEY_FILE = "private_key.pem"
input_files = ARGV
if input_files.empty?
abort "Usage: sign-pdf input.pdf [...]"
end
key = OpenSSL::PKey::RSA.new(File.read(KEY_FILE))
cert = OpenSSL::X509::Certificate.new(File.read(CERT_FILE))
input_files.each do |file|
output_filename = file.dup.insert(file.rindex("."), "_signed")
pdf = PDF.read(file)
page = pdf.get_page(1)
width = 200.0
height = 50.0
x = page.MediaBox[2].to_f - width - height
y = height
size = 8
now = Time.now
text_annotation = Annotation::AppearanceStream.new
text_annotation.Type = Origami::Name.new("XObject")
text_annotation.Resources = Resources.new
text_annotation.Resources.ProcSet = [Origami::Name.new("Text")]
text_annotation.set_indirect(true)
text_annotation.Matrix = [ 1, 0, 0, 1, 0, 0 ]
text_annotation.BBox = [ 0, 0, width, height ]
text_annotation.write("Signed at #{now.iso8601}", x: size, y: (height/2)-(size/2), size: size)
# Add signature annotation (so it becomes visibles in PDF document)
signature_annotation = Annotation::Widget::Signature.new
signature_annotation.Rect = Rectangle[llx: x, lly: y+height, urx: x+width, ury: y]
signature_annotation.F = Annotation::Flags::PRINT
signature_annotation.set_normal_appearance(text_annotation)
page.add_annot(signature_annotation)
# Sign the PDF with the specified keys
pdf.sign(cert, key,
method: "adbe.pkcs7.sha1",
annotation: signature_annotation,
location: "Helsinki",
contact: "[email protected]",
reason: "Proof of Concept"
)
# Save the resulting file
pdf.save(output_filename)
end
@dprodrigueza
Copy link

I need help with this, when using this method with a .p12 file, I have the problem that in the KeyUsage it only uses Key Encryption, I need the KeyUsage to be digital signature and not repudiation, any help?

@matiaskorhonen
Copy link
Author

Sorry, can't help you out there as I haven't needed to touch PDF signing stuff in years and years now…

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment