How to extract the IV vector generated by encrypt method from encrypted_strings

后端 未结 1 1727
礼貌的吻别
礼貌的吻别 2021-01-28 04:49

I\'m having troubles to extract the IV generated with the encrypt method from encrypted_strings library for a specific password I provide. From the doc

1条回答
  •  后悔当初
    2021-01-28 05:04

    PKCS7 padding is basically the same as PKCS5. The reason you get a different result on the command line is that it only uses a single hash iteration, where the function used by encrypted_strings does 2048 iterations by default.

    The function used, EVP_BytesToKey is described in the OpenSSL wiki, which include details of the algorithm. Reproducing it in Ruby might look something like this (using MD5 and 2048 iterations):

    def hash(d, count)
      count.times do
        d = OpenSSL::Digest.digest('md5', d)
      end
      d
    end
    
    password = 'bAJLyifeUJUBFWdHzVbykfDmPHtLKLMzViHW9aHGmyTLD8hGYZ'
    
    bytes = ''
    last = ''
    
    # For des-ede3-cbc, 24 byte key + 8 byte IV = 32 bytes.
    while bytes.length < 32
      last = hash(last + password, 2048)
      bytes << last
    end
    
    key = bytes[0...24]
    iv = bytes[24..-1]
    

    You can use these values to decrypt the result of your code (add require 'base64' first):

    # This is the result of your code:
    encrypted_data = "AEsDXVcgh2jsTjlDgh+REg=="
    
    # enrypted_strings produces base64 encoded results, so we decode first
    encrypted_data = Base64.decode64(encrypted_data)
    
    cipher = OpenSSL::Cipher.new('des-ede3-cbc')
    cipher.decrypt
    cipher.key = key
    cipher.iv = iv
    
    plain = cipher.update(encrypted_data) + cipher.final
    
    puts plain #=> "Whackabad"
    

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