aperture aperture - 5 months ago 39
Ruby Question

Ruby OpenSSL unable to decrypt

I am able to encrypt files, but when I try to decrypt them I am getting "error reading input file". I am using a public/private keypair to encrypt the passphrase that is used in encrypting the file. This is so that only the owner of the private key is able to decrypt the file.

My encryption method uses the Ruby OpenSSL module and looks like:

file = params[:submission][:report].path
filename = params[:submission][:report].original_filename.gsub(" ", "_")

pubkey = OpenSSL::PKey::RSA.new File.read "#{Rails.root.to_s}/key/pubkey.pem"
cipher = OpenSSL::Cipher.new("aes-256-cbc")
cipher.encrypt
cipher.key = key = (0...50).map{ ('a'..'z').to_a[rand(26)] }.join

buf = ""
File.open("#{Rails.root.to_s}/evidence/#{filename}.enc", "wb") do |outf|
File.open(file, "rb") do |inf|
while inf.read(4096, buf)
outf << cipher.update(buf)
end
outf << cipher.final
end
end

encrypted_key = pubkey.public_encrypt key
File.open("#{Rails.root.to_s}/evidence/#{filename}_passphrase.bin", 'wb') {|f| f.write(encrypted_key) }


Then I am using openssl in a Linux environment to handle the decrypting

openssl rsautl -in file_passphrase.bin -out passphrase.txt -inkey privkey.pem -decrypt
openssl enc -a -d -aes-256-cbc -in file.enc -out file.pdf -pass file:passphrase.txt


I have also tried using a salt, encrypting/decrypting it the same as the passphrase, and I get the same error.

What am I doing wrong here?

Thanks

Answer

Not exactly a solution, but this works. Instead of the OpenSSL module, I'm just using system commands:

file = params[:submission][:report].path
filename = params[:submission][:report].original_filename.gsub(" ", "_")
passphrase = (0...50).map{ ('a'..'z').to_a[rand(26)] }.join
system("openssl enc -a -e -aes-256-cbc -in #{file} -out #{Rails.root.to_s}/evidence/#{filename}.asc -pass pass:#{passphrase}")
system("echo #{passphrase} | openssl rsautl -out #{Rails.root.to_s}/evidence/#{filename}_password.bin -pubin -inkey #{Rails.root.to_s}/key/pubkey.pem -encrypt")

Then using the same decryption method as in the question.