尝试在ruby中加密时如何存储创建的随机密钥和iv?

发布时间:2020-07-06 00:18

我目前正在一个项目中,我将把用户数据存储在文本文件中。我想使用Ruby中的OpenSSL库对这些文件进行加密。我能够使用随机创建的密钥和iv值加密文件。由于该程序不会在服务器上运行,而是在本地运行,因此我想使用密码导出这些值,以便使用其他方法可以解密信息。

require "openssl"

cipher = OpenSSL::Cipher::AES256.new(:CBC)
cipher.encrypt

key = cipher.random_key

iv = cipher.random_iv
encrypted = cipher.update("test.txt") + cipher.final
File.open("temp.txt", "w+") do |file|
    file.write(encrypted)
end

如果我不使用随机密钥,它将不会加密信息或返回错误。

'update': key not set (OpenSSL::Cipther::CipherError)

当我尝试使用导出命令(带有随机键)时,我还收到一条错误消息,指出它不是方法。

'export' for #<string:0x00000000065659b8> (NoMethodError)
回答1

看来您没有开发加密方案的经验,所以我建议您不要自己实现此方案。内置的OpenSSL库无法防止您犯安全错误。正如您所注意到的,它没有提供有关如何安全处理密钥和iv的指导(并且错误地进行操作将是不安全的)。

我建议使用 .replace(/\\n/gm, '\n')宝石,它具有:

rbnacl类提供了一个简单易用的加密API,其中所有困难的决定都是事先为您制定的。如果您想加密某些东西,而您对密码学的了解不多,那可能就是您想要使用的东西。

这是一个完整的端到端示例,可输出到磁盘并从磁盘加载:

RbNaCl::SimpleBox

请注意,require 'rbnacl' generated_key = RbNaCl::Random.random_bytes(RbNaCl::SecretBox.key_bytes) box = RbNaCl::SimpleBox.from_secret_key(generated_key) ciphertext = box.encrypt('plaintext') # save both artifacts to disk File.open('cipher.bin', 'w') { |f| f.write(ciphertext) } File.open('key.bin', 'w') { |f| f.write(generated_key) } # decrypt by reading artifacts from disk # this could be done in separate program ciphertext_from_file = File.read('cipher.bin', mode: 'rb') # r -> "read", b -> "binary" key_from_file = File.read('key.bin', mode: 'rb') regenerated_box = RbNaCl::SimpleBox.from_secret_key(key_from_file) regenerated_box.decrypt(ciphertext_from_file) # => 'plaintext' # cleanup File.delete('cipher.bin') if File.exist?('cipher.bin') File.delete('key.bin') if File.exist?('key.bin') generated_key都是二进制字符串。如果您不想保存原始二进制文件,请使用ciphertextBase64.encode64之类的文件将其转换为可打印字符。这样,它们将可打印,可复制/粘贴,并且您无需使用Digest.hexencode进行“读取二进制文件”。