Search code examples
phpruby-on-railsrubyencryptionmcrypt

Decrypting PHP MCRYPT_RIJNDAEL_256 in Ruby


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)));
}

Solution

  • 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.