Decrypting PHP MCRYPT_RIJNDAEL_256 in Ruby

六月ゝ 毕业季﹏ 提交于 2019-12-09 21:21:40

问题


I have a database filled with encrypted passwords that I need to decrypt in Ruby for a platform change. How can I port this PHP code to Ruby? Have tried to use OpenSSL in Ruby with AES_256 but getting 'Bad Decrypt' errors and also errors that my key ($salt) isn't long enough.

In the example below, $salt is a 25 character string.

This is the PHP decryption function:

function decrypt_password($text, $salt)
{
    return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256,
        $salt, base64_decode($text), MCRYPT_MODE_ECB, 
        mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB),
        MCRYPT_RAND)));
}

回答1:


MCRYPT_RIJNDAEL_256 algorithm does not implement AES, it implements Rijndael using a 256 bit block size. This is not a default mode, you can find an implementation for Ruby here.

Furthermore, you seem to be using the $salt variable as a key. Keys are automatically extended to the next available key size. For 25 byte keys I presume a 256 bit (32 byte) key will be used. This is the $salt value, extended with bytes valued 00. Note that I'm presuming that each character is encoded as a single byte on your system.

As a final surprise, you may safely disregard the mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND) part of the code, as ECB mode does not use an IV, so the value it returns is fully ignored. Note that using ECB mode for strings - and therefore also passwords of course - is not secure.

You should, at the very minimum use AES CBC with a random IV. And you should consider using bcrypt instead of encryption if you don't need the value of the passwords itself.




回答2:


There is a ruby library for mcrypt as well. See below for a sample implementation:

require 'mcrypt'
require 'base64'

# base64_decode() equivalent
encrypted = Base64.decode64(text)

# preparing Mcrypt library for Rijndael cipher, 256 bits, ECB mode
cipher = Mcrypt.new(:rijndael_256, :ecb, salt, nil, :zeros)

# padding required
encrypted = encrypted.ljust((encrypted.size / 32.0).ceil * 32, "\0") 

# decrypt using Rijndael
decrypted = cipher.decrypt(encrypted).strip

Dependencies: libmcrypt

  • sudo apt-get install libmcrypt-dev (Ubuntu/Debian)
  • sudo yum install libmcrypt-devel (RHEL/CentOS/Fedora)

Gems: mcrypt

  • gem install ruby-mcrypt


来源:https://stackoverflow.com/questions/23745059/decrypting-php-mcrypt-rijndael-256-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!