2013-04-12 64 views
1

我能夠加密文件,但是當我嘗試解密它們時,出現「讀取輸入文件時出錯」。我正在使用公鑰/私鑰對來加密用於加密文件的密碼短語。這樣只有私鑰的所有者才能解密該文件。Ruby OpenSSL無法解密

我的加密方法是使用紅寶石OpenSSL的模塊,看起來像:

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) } 

然後我使用OpenSSL的Linux環境處理解密

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 

我還使用鹽嘗試,加密/解密它與密碼相同,並且我得到相同的錯誤。

我在這裏做錯了什麼?

謝謝

回答

0

不完全是一個解決方案,但這個工程。代替OpenSSL模塊,我只使用系統命令:

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") 

然後使用與問題中相同的解密方法。

0

您的加密文件是base64編碼的。如果行長度超過64個字符,則openssl在撤銷base64編碼時遇到問題,並在輸入文件時輸出錯誤。我不確定問題是否存在於所有版本的openssl中。

兩種解決方案浮現在腦海中:

  • 的base64與其他實用程序首先解碼文件,然後不帶-a開關
  • 運行openssl enc命令在加密和每次的base64 64個字符後插入一個換行符編碼文件(在你的例子中是file.enc)