簡體   English   中英

如何使用Ruby加密文件?

[英]How to encrypt files with Ruby?

我需要編寫一個加密/解密文件的簡單工具。

我想最好的方法是使用OpenSSL:

生成密鑰:

openssl rand -base64 2048 > secret_key

加密文件:

openssl aes-256-cbc -a -e -in file -out file.enc -k secret_key

解密文件:

openssl aes-256-cbc -d -in file.enc -out file -k secret_key

有沒有一種簡單的方法在Ruby中實現它? 有沒有更好的方法呢? 使用PGP可能嗎?

Ruby的OpenSSL是OpenSSL本身的一個薄包裝器,它提供了OpenSSL本身所具有的幾乎所有功能,所以是的,所有示例都有一對一的映射:

openssl rand -base64 2048 > secret_key

這實際上是誇大了,你使用的是AES-256,所以你只需要一個256位密鑰,這里你沒有使用RSA。 Ruby OpenSSL不需要這個決定,它會根據你想要使用的算法自動確定正確的密鑰大小。

您在加密過程中也犯了使用確定性IV的錯誤。 為什么? 因為您根本沒有指定IV,所以OpenSSL本身將默認為所有零字節的IV。 這不是一件好事,所以我將向您展示正確的方法,有關更多信息,請查看Cipher文檔

require 'openssl'

# encryption
cipher = OpenSSL::Cipher.new('aes-256-cbc')
cipher.encrypt
key = cipher.random_key
iv = cipher.random_iv

buf = ""
File.open("file.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

# decryption
cipher = OpenSSL::Cipher.new('aes-256-cbc')
cipher.decrypt
cipher.key = key
cipher.iv = iv # key and iv are the ones from above

buf = ""
File.open("file.dec", "wb") do |outf|
  File.open("file.enc", "rb") do |inf|
    while inf.read(4096, buf)
      outf << cipher.update(buf)
    end
    outf << cipher.final
  end
end

正如您所看到的,加密和解密非常相似,因此您可以將流式讀/寫組合成一個共享方法,並將其傳遞給正確配置的Cipher加上相應的文件名,為了清楚起見,我只是明確地說明了。

如果你想對密鑰進行Base64編碼(也可能是IV),你可以使用Base64模塊:

base64_key = Base64.encode64(key)

Ruby有一個OpenSSL庫 ,可以解決繁重的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM