Decrypting salted AES file generated on command line with Ruby

前端 未结 1 997
粉色の甜心
粉色の甜心 2020-12-11 08:19

I would like to decrypt a text file within a ruby 2.1 script which was previously encrypted using OpenSSL\'s commandline tools: openssl enc -aes-256-cbc -a -salt -in m

1条回答
  •  有刺的猬
    2020-12-11 08:48

    OpenSSL uses a custom header and key derivation routine. Security.SE has a good description of the header and the docs for EVP_BytesToKey describe the key derivation.

    We can modify your code to use this weird and somewhat broken key derivation as follows:

    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
    

    0 讨论(0)
提交回复
热议问题