Insert digital signature into existing pdf file - ruby

I need to insert a digital signature into already existing pdf files, using a rails application server. (Basically, clients upload pdf files and the server signs them with a local certificate)
I've been using JSignpdf to insert digital signatures into pdf files, and started probing for gems for ruby...
I've found another portable file to do this job on rubypdf site http://soft.rubypdf.com/software/pdf-digital-signe, but cannot find any gem or even example code to do this in ruby.
I've looked also at Digital signature verification with OpenSSL, but couldn't understand how to actually sign an already existing document, with a local certificate file.
I also took a peak at http://code.google.com/p/origami-pdf/ , but this seems a bit harsh for a supposingly "simple" (at least in concept) task.
Any ideas/suggestions?
Thank you

After some research, recurring to the OpenSSL documentation and exploring the Origami solution, i built the code below, and managed to insert a locally generated signature/certificate into a pdf document. Now I just need to figure out how to use this with an external generated certificate (check version 2 below, where i solved it). I've opened a new question where you can find some details on a difficulty i had with OpenSSL and DER encoded certificates.
To develop version 2, i also spent some time wondering how to add an annotation - so the signature becomes visible in Adobe reader - without adding a new page to the document. From origami documentation, i found the get_page method, which solved my last problem on this. I'm using Adobe Reader X, for the record.
Hope you find this useful as I will ;-).
VERSION 1 - Generate certificate and key file, and insert them directly into the document
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
# Code below is based on documentation available on
# http://www.ruby-doc.org/stdlib-1.9.3/libdoc/openssl/rdoc/OpenSSL.html
key = OpenSSL::PKey::RSA.new 2048
open 'private_key.pem', 'w' do |io| io.write key.to_pem end
open 'public_key.pem', 'w' do |io| io.write key.public_key.to_pem end
cipher = OpenSSL::Cipher::Cipher.new 'AES-128-CBC'
pass_phrase = 'Origami rocks'
key_secure = key.export cipher, pass_phrase
open 'private_key.pem', 'w' do |io|
io.write key_secure
end
#Create the certificate
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
OUTPUTFILE = "test.pdf"
contents = ContentStream.new.setFilter(:FlateDecode)
contents.write OUTPUTFILE,
:x => 350, :y => 750, :rendering => Text::Rendering::STROKE, :size => 30
pdf = PDF.read('Sample.pdf')
# Open certificate files
#sigannot = Annotation::Widget::Signature.new
#sigannot.Rect = Rectangle[:llx => 89.0, :lly => 386.0, :urx => 190.0, :ury => 353.0]
#page.add_annot(sigannot)
# Sign the PDF with the specified keys
pdf.sign(cert, key,
:method => 'adbe.pkcs7.sha1',
#:annotation => sigannot,
:location => "Portugal",
:contact => "myemail#email.tt",
:reason => "Proof of Concept"
)
# Save the resulting file
pdf.save(OUTPUTFILE)
VERSION 2 - Use existing certificates to sign a pdf document
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
INPUTFILE = "Sample.pdf"
#inputfile = String.new(INPUTFILE)
OUTPUTFILE = #inputfile.insert(INPUTFILE.rindex("."),"_signed")
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)
pdf = PDF.read(INPUTFILE)
page = pdf.get_page(1)
# Add signature annotation (so it becomes visibles in pdf document)
sigannot = Annotation::Widget::Signature.new
sigannot.Rect = Rectangle[:llx => 89.0, :lly => 386.0, :urx => 190.0, :ury => 353.0]
page.add_annot(sigannot)
# Sign the PDF with the specified keys
pdf.sign(cert, key,
:method => 'adbe.pkcs7.sha1',
:annotation => sigannot,
:location => "Portugal",
:contact => "myemail#email.tt",
:reason => "Proof of Concept"
)
# Save the resulting file
pdf.save(OUTPUTFILE)

If you're working on a project for pay, you might want to consider jPDFSecure, a commercial Java library built for developers to digitally sign PDF documents and change security settings on PDF Documents. With jPDFSecure, your application or java applet can encrypt PDF documents, set permissions and passwords, and create and apply digital signatures. jPDFSecure is optimized for performance and is built on top of Qoppa's proprietary PDF technology so there is no need for any third party software or drivers.
jPDFSecure has a simple interface to load PDF documents from files, network drives,URLs and even input streams, which can be generated runtime or come directly from a database. After changing security settings, jPDFSecure can save the document to a file, a java.io.OutputStream or a javax.servlet.ServletOutputStream when running in a Java EE application server to output the file directly to a browser.
jPDFSecure is platform independent and can be used in any environment that supports Java, including Windows, Mac OSX and Linux.

Related

Unable to upload and image in googledrive using goolge ruby API

I am first time using Google APIs. I am unable to upload any file in Google Drive. I tried below complete code.
require 'google/apis/drive_v2'
require 'google/api_client/client_secrets'
# I downloaded 'client_secrets.json' file from 'https://console.developers.google.com/projectselector/apis/library' and put in lib folder
CLIENT_SECRETS_FILE = "client_secrets.json"
client_secrets_filepath = File.expand_path(CLIENT_SECRETS_FILE ,"#{File.dirname(__FILE__)}/../../lib/")
CLIENT_SECRETS = Google::APIClient::ClientSecrets.load(client_secrets_filepath)
authorization = CLIENT_SECRETS.to_authorization
Drive = Google::Apis::DriveV2
#drive = Drive::DriveService.new
#drive.authorization = authorization
file_path = File.expand_path(#ScreenShot_dir)+'/'+"imageName" +'.png'
metadata = Drive::File.new(title: 'My document')
metadata = #drive.insert_file(metadata, upload_source: file_path, content_type: 'image/png')
It is not uploading the file in drive but giving an error like "missing authorization code".
my client_secrets.json look like below:
{"installed":{
"client_id":"<some digits>.apps.googleusercontent.com",
"project_id":"<projectname>","auth_uri":"https://accounts.google.com/o/oauth2/auth",
"token_uri":"https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
"client_secret":"<secret key>",
"redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]}}
I am not sure what I am missing in it. Appreciate any help on this issue.
"missing authorization code"
Means that you have not properly authenticated your code.
You should check the Ouath2 documentation for the client library. Get one of the samples there working then you should be able to alter it for Drive without to much trouble.
# AdSense Management API command-line sample.
require 'google/apis/adsense_v1_4'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/installed_app'
require 'google/api_client/auth/storage'
require 'google/api_client/auth/storages/file_store'
require 'logger'
require 'json'
CREDENTIAL_STORE_FILE = "#{$0}-oauth2.json"
# Handles authentication and loading of the API.
def setup
log_file = File.open('adsense.log', 'a+')
log_file.sync = true
logger = Logger.new(log_file)
logger.level = Logger::DEBUG
adsense = Google::Apis::AdsenseV1_4::AdSenseService.new
# Stores auth credentials in a file, so they survive multiple runs
# of the application. This avoids prompting the user for authorization every
# time the access token expires, by remembering the refresh token.
# Note: FileStorage is not suitable for multi-user applications.
storage = Google::APIClient::Storage.new(
Google::APIClient::FileStore.new(CREDENTIAL_STORE_FILE))
adsense.authorization = storage.authorize
if storage.authorization.nil?
client_secrets = Google::APIClient::ClientSecrets.load
# The InstalledAppFlow is a helper class to handle the OAuth 2.0 installed
# application flow, which ties in with Stroage to store credentials
# between runs.
flow = Google::APIClient::InstalledAppFlow.new(
:client_id => client_secrets.client_id,
:client_secret => client_secrets.client_secret,
:scope => ['https://www.googleapis.com/auth/adsense.readonly']
)
adsense.authorization = flow.authorize(storage)
end
return adsense
end
# Generates a report for the default account.
def generate_report(adsense)
report = adsense.generate_report(start_date: '2011-01-01', end_date: '2011-08-31',
metric: %w(PAGE_VIEWS AD_REQUESTS AD_REQUESTS_COVERAGE
CLICKS AD_REQUESTS_CTR COST_PER_CLICK
AD_REQUESTS_RPM EARNINGS),
dimension: %w(DATE),
sort: %w(+DATE))
# Display headers.
report.headers.each do |header|
print '%25s' % header.name
end
puts
# Display results.
report.rows.each do |row|
row.each do |column|
print '%25s' % column
end
puts
end
end
if __FILE__ == $0
adsense = setup()
generate_report(adsense)
end

How to verify PDF digital signature in Ruby

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?

Encrypt data bag from inside of ruby without relying on knife

At the moment to encrypt a data bag, I have to do :
system "knife data bag from file TemporaryEncrypting \"#{enc_file_path}\" --secret-file #{Secret_Key_Path}"
and that doesn't work because knife can't find a config file and I can't seem to get it read the one in C:\chef.
How do I do this from within ruby?
I worked out how to encrypt inside of ruby, just use this code:
require 'chef/knife'
#require 'chef/encrypted_data_bag_item' #you need to do this in chef version 12, they've moved it out of knife and into it's own section
require 'json'
secret = Chef::EncryptedDataBagItem.load_secret Secret_Key_Path
to_encrypt = JSON.parse(json_to_encrypt)
encrypted_data = Chef::EncryptedDataBagItem.encrypt_data_bag_item to_encrypt, secret
Answer achieved with information from this answer, here is the code in question:
namespace 'databag' do
desc 'Edit encrypted databag item.'
task :edit, [:databag, :item, :secret_file] do |t, args|
args.with_defaults :secret_file => "#{ENV['HOME']}/.chef/encrypted_data_bag_secret"
secret = Chef::EncryptedDataBagItem.load_secret args.secret_file
item_file = "data_bags/#{args.databag}/#{args.item}.json"
tmp_item_file = "/tmp/#{args.databag}_#{args.item}.json"
begin
#decrypt data bag into tmp file
raw_hash = Chef::JSONCompat.from_json IO.read item_file
databag_item = Chef::EncryptedDataBagItem.new raw_hash, secret
IO.write tmp_item_file, Chef::JSONCompat.to_json_pretty( databag_item.to_hash )
#edit tmp file
sh "#{ENV['EDITOR']} #{tmp_item_file}"
#encrypt tmp file data bag into original file
raw_hash = Chef::JSONCompat.from_json IO.read tmp_item_file
databag_item = Chef::EncryptedDataBagItem.encrypt_data_bag_item raw_hash, secret
IO.write item_file, Chef::JSONCompat.to_json_pretty( databag_item )
ensure
::File.delete tmp_item_file #ensure tmp file deleted.
end
end
end

getting BadDigest error while trying to upload compressed file to s3 on ruby 1.9.3

as stated, i am trying to upload a file to s3
require 'digest/md5'
require 'base64'
require 'aws-sdk'
def digest f
f.rewind
Digest::MD5.new.tab do |dig|
f.each_chunk{|ch| dig << ch}
end.base64digest
ensure
f.rewind
end
file = File.new(compress file) #file zipped with zip/zip
total = file.size
digest = digest(file)
s3 = AWS::S3::new(:access_key_id => #access_key_id, :secret_access_key
=> #secret_access_key)
bucket = s3.buckets['mybucket']
bucket.objects["myfile"].write :content_md5 => digest, :content_length
=> total do |buf,len|
buf.write(file.read len)
end
but i constantly get AWS::S3::Errors::BadDigest exception
if i try to upload the file without passing :content_md5, everything goes well, archive downloads and opens correctly.
also as i just found out this fails on ruby 1.9.3 but works well on 1.9.2
fixed by changing digest func to
def digest f
Digest::MD5.file(f.path).base64digest
end
i think the issue was in the fact that the file passed to it was open

Using aws-sdk to download files from s3. Encoding not right

I am trying to use aws-sdk to load s3 files to local disk, and question why my pdf file (which just has a text saying SAMPLE PDF) turns out with an apparently empty content.
I guess it has something to do with the encoding...but how can i fix it?
Here is my code :
require 'aws-sdk'
bucket_name = "****"
access_key_id = "***"
secret_access_key = "**"
s3=AWS::S3.new(
access_key_id: access_key_id,
secret_access_key: secret_access_key)
b = s3.buckets[bucket_name]
filen = File.basename("Sample.pdf")
path = "original/90/#{filen}"
o = b.objects[path]
require 'tempfile'
ext= File.extname(filen)
file = File.open("test.pdf","w", encoding: "ascii-8bit")
# streaming download from S3 to a file on disk
begin
file.write(o.read) do |chunk|
file.write(chunk)
end
end
file.close
If i take out the encoding: "ascii-8bit", i just get an error message Encoding::UndefinedConversionError: "\xC3" from ASCII-8BIT to UTF-8
After some research and a tip from a cousin of mine, i finally got this to work.
Instead of using the aws solution to load the file from amazon and write it to disk (which was generating a strange pdf file : apparently equal to the original, but with blank content, and Adobe Reader "fixing" it when opening)
i instead am now using open-uri, with SSL ignore.
Here is the final code which made my day :
require 'open-uri'
open('test.pdf', 'wb') do |file|
file << open('https://s3.amazon.com/mybucket/Sample.pdf',:ssl_verify_mode => OpenSSL::SSL::VERIFY_NONE).read
end

Resources