Decrypting PHP MCRYPT_RIJNDAEL_256 in Ruby

2019-04-14 05:20发布

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

2条回答
Melony?
2楼-- · 2019-04-14 06:03

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
查看更多
Summer. ? 凉城
3楼-- · 2019-04-14 06:07

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.

查看更多
登录 后发表回答