Skip to content

Instantly share code, notes, and snippets.

@tbcooney
Last active June 9, 2020 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tbcooney/045842b735e456343ee4cb96f7fc40d6 to your computer and use it in GitHub Desktop.
Save tbcooney/045842b735e456343ee4cb96f7fc40d6 to your computer and use it in GitHub Desktop.
require 'openssl'
begin
require 'origami'
rescue LoadError
# ORIGAMIDIR = "C:\RailsInstaller\Ruby1.9.3\lib\ruby\gems\1.9.1\gems\origami-1.2.4\lib"
# $: << ORIGAMIDIR
# require 'origami'
end
include Origami
OUTPUT_FILE = "#{File.basename(__FILE__, ".rb")}.pdf"
CERTFILE = "certificate.pem"
RSAKEYFILE = "private_key.pem"
passphrase = "your passphrase"
key4pem=File.read RSAKEYFILE
key = OpenSSL::PKey::RSA.new key4pem, passphrase
cert = OpenSSL::X509::Certificate.new(File.read CERTFILE)
# Create the PDF contents
contents = ContentStream.new.setFilter(:FlateDecode)
contents.write OUTPUT_FILE,
x: 350, y: 750, rendering: Text::Rendering::STROKE, size: 30
pdf = PDF.new
page = Page.new.setContents(contents)
pdf.append_page(page)
sig_annot = Annotation::Widget::Signature.new
sig_annot.Rect = Rectangle[llx: 89.0, lly: 386.0, urx: 190.0, ury: 353.0]
page.add_annotation(sig_annot)
# Sign the PDF with the specified keys
pdf.sign(cert, key,
method: 'adbe.pkcs7.detached',
annotation: sig_annot,
location: "France",
contact: "gdelugre@localhost",
reason: "Signature sample"
)
# Save the resulting file
pdf.save(OUTPUT_FILE)
puts "PDF file saved as #{OUTPUT_FILE}."
@tbcooney
Copy link
Author

tbcooney commented Jun 9, 2020

Sample Ruby code works with Amazon CloudHSM:

require 'openssl'
require 'base64'

FAKE_KEY = "/root/ruby/ruby_key_inside_hsm/ruby_hsm_fake_private.key"
REAL_KEY = "/root/ruby/ruby_key_inside_hsm/ruby_hsm_real_private_exported.key"
PUB_KEY = "/root/ruby/ruby_key_inside_hsm/pubkey.pem"

STR = "test string"

def encrypt(str)
  pubkey = OpenSSL::PKey::RSA.new(File.read(PUB_KEY))
  Base64.encode64(pubkey.public_encrypt(str))
end

def decrypt(str, key)
  OpenSSL::Engine.load
  privkey = OpenSSL::PKey::RSA.new(File.read(key))
  privkey.private_decrypt(Base64.decode64(str))
end


def estr
  encrypt(STR)
end

def real_dec
  decrypt(estr, REAL_KEY)
end

def hsm_dec
  OpenSSL::Engine.load
  OpenSSL::Engine.by_id('cloudhsm')
  decrypt(estr, FAKE_KEY)
end

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