How to verify PDF digital signature in Ruby

喜夏-厌秋 提交于 2019-12-24 03:26:26

问题


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?

来源:https://stackoverflow.com/questions/43229221/how-to-verify-pdf-digital-signature-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!