解密使用Ruby在命令行上生成的salted AES文件

前端之家收集整理的这篇文章主要介绍了解密使用Ruby在命令行上生成的salted AES文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想解密以前使用OpenSSL命令行工具加密的ruby 2.1脚本中的文本文件
openssl enc -aes-256-cbc -a -salt -in my_file

如命令中所示,该文件是AES-256-CBC加密,盐渍和base64编码.

密码是已知的,但不是IV和密钥,这是从ruby documentation获取的遵循此代码段所必需的:

decipher = OpenSSL::Cipher::AES.new 256,:CBC
decipher.decrypt
decipher.key = key
decipher.iv = iv

plain = decipher.update(encrypted_text) + decipher.final

在试图找到答案的同时,我发现了gem AESCrypt gem,它可以简化en-and decrypting,但目前发布的版本与ruby 2.1不兼容.
看着它的源代码,我发现密钥是retrieved by digesting the passwordIV is just left as nil.

所以我尝试了以下运行:

encoded_and_encrypted_text = File.read my_file_path
encrypted_text = Base64.decode64 encoded_and_encrypted_text.to_s.strip

decipher = OpenSSL::Cipher::AES.new 256,:CBC
decipher.decrypt

decipher.key = OpenSSL::Digest::SHA256.new(my_password).digest

plain_text = decipher.update(encrypted_text) + decipher.final

但这会导致OpenSSL :: Cipher :: CipherError:解密错误.

我是否需要以某种方式专门处理文件被腌制?我在OpenSSL documentation for the enc function中读到,如果在加密文件时未指定IV,则从密码生成.我需要以某种方式手动重建IV吗?

任何建议将受到高度赞赏:)

解决方法

OpenSSL使用自定义标头和密钥派生例程. Security.SE has a good description of the headerdocs for EVP_BytesToKey描述了密钥推导.

我们可以修改你的代码,使用这个奇怪的,有点破坏的密钥派生如下:

encoded_and_encrypted_text = File.read my_file_path
encrypted_text = Base64.decode64 encoded_and_encrypted_text.to_s.strip

header = encrypted_text[0,8]
salt = encrypted_text[8,8]
payload = encrypted_text[16..-1]

decipher = OpenSSL::Cipher::AES.new 256,:CBC
decipher.decrypt

D_1 = OpenSSL::Digest::MD5.new(my_password + salt).digest
D_2 = OpenSSL::Digest::MD5.new(D_1 + my_password + salt).digest
D_3 = OpenSSL::Digest::MD5.new(D_2 + my_password + salt).digest

decipher.key = (D_1 + D_2)
decipher.iv = D_3

plain_text = decipher.update(payload) + decipher.final
原文链接:https://www.f2er.com/ruby/274063.html

猜你在找的Ruby相关文章