Ruby 的 OpenSSL 是 OpenSSL 本身的一个精简包装器,并提供了几乎所有 OpenSSL 本身的功能,所以是的,您的所有示例都有一个一对一的映射:
openssl rand -base64 2048 > secret_key
这其实有点夸张,你使用的是 AES-256,所以你只需要一个 256 位的密钥,你这里没有使用 RSA。 Ruby OpenSSL 将这个决定从您的肩上卸下,它会根据您要使用的算法自动确定正确的密钥大小。
您也犯了在加密期间使用确定性 IV 的错误。为什么?因为您根本没有指定 IV,所以 OpenSSL 本身将默认为全零字节的 IV。这不是一件好事,所以我将向您展示正确的方法,更多信息请查看Cipher documentation。
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 加上相应的文件名传递给它,我只是明确说明了它们为了清楚起见。
如果您想对密钥(可能还有 IV)进行 Base64 编码,您可以使用 Base64 模块:
base64_key = Base64.encode64(key)