2
votes

I added a digital signature as mentioned in "Insert digital signature into existing pdf file" and stored that certificate as a PEM file in local. How can I verify the signature with a stored certificate?

This is sample code from source:

open 'certificate.pem', 'w' do |io| io.write cert.to_pem end #Saving certificate
cert = OpenSSL::X509::Certificate.new(File::read('certificate.pem')) #Opening certificate to verify. This gives error. how to convert pem string to certificate.
pdf = PDF.read('test.pdf') #opening certified pdf to validate signature
pdf.verify(trusted_certs: [cert]) if pdf.signed? #This gives error.

Edited: After adding cert.sign key, OpenSSL::Digest::SHA1.new the above works.But the verification fails. Using the following code i added digital signature into pdf.

require 'openssl'
require 'origami'
include Origami
key = OpenSSL::PKey::RSA.new 2048
name = OpenSSL::X509::Name.parse 'CN=nobody/DC=example'
cert = OpenSSL::X509::Certificate.new
cert.version = 2
cert.serial = 0
cert.not_before = Time.now
cert.not_after = Time.now + 3600
cert.public_key = key.public_key
cert.subject = name
cert.sign key, OpenSSL::Digest::SHA1.new
open 'certificate.pem', 'w' do |io| io.write cert.to_pem end
OUTPUTFILE = "outfile.pdf"
pdf = PDF.read('testing.pdf')
pdf.sign(cert, key, 
  :method => 'adbe.pkcs7.sha1',
  #:annotation => sigannot, 
  :location => "Portugal", 
  :contact => "[email protected]", 
  :reason => "Proof of Concept"
)
pdf.save(OUTPUTFILE)

After that i used the following code to verify digital signature using stored certificate. But it gives false.

signed_cert = OpenSSL::X509::Certificate.new(File::read('certificate.pem'))
pdf = PDF.read("outfile.pdf")
if pdf.signed?
  pdf.verify(trusted_certs: [signed_cert]) #This gives false
end

What am I doing wrong?

It might help if you state the error.Kris
Please read "minimal reproducible example" and the linked page.the Tin Man
I answered a similar question here How to add digital signature to pdf in Ruby? It's a bit rough of an answer but it has all the elements you're looking for.Harry Fairbanks