2

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 => "myemail@email.tt", 
  :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?

Community
  • 1
  • 1
Gurunath
  • 341
  • 3
  • 17
  • It might help if you state the error. – Kris Apr 05 '17 at 11:51
  • Please read "[mcve]" and the linked page. – the Tin Man Apr 05 '17 at 19:46
  • I answered a similar question here [How to add digital signature to pdf in Ruby?](https://stackoverflow.com/questions/51984805/origami-openssl-error-while-validating-digital-signature-of-a-pdf-in-rails/54526938#54526938) It's a bit rough of an answer but it has all the elements you're looking for. – Harry Fairbanks Feb 05 '19 at 02:16

0 Answers0