MCrypt rijndael-256 to OpenSSL aes-256-ecb conversion

北战南征 提交于 2019-12-30 09:32:30

问题


Since Mcrypt is deprecated, I want to use OpenSSL instead in my code since we already using php 7.2.4 in our server.

I have used following code for Encryption/Decryption.

//ENCRYPTION

function encrypt($text, $salt='') {
        if ($text == "") return "";
        if ($salt == "") $salt = 'DiAo74dOO09T48YESmuvbS0T';
        return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $salt, $text, MCRYPT_MODE_ECB, mcrypt_create_iv   

(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
    }

//DECRYPTION

function decrypt($text, $salt = '') {
        if ($text == "")
            return "";
        if ($salt == "")
            $salt = 'DiAo74dOO09T48YESmuvbS0T';
        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)));
    }

"AFdT9sa81krHkp/GoYCSwh7/lZn/gLZLHJSldi5/QCU=" This String I had encrypted using above encryption function, But I want it to decrypt it using OPENSSL. I used following code to decrypt it.

    $string = 'AFdT9sa81krHkp/GoYCSwh7/lZn/gLZLHJSldi5/QCU=';   
    $output = false;
    $secret_key = 'DiAo74dOO09T48YESmuvbS0T';   
    $secret_iv1 = openssl_random_pseudo_bytes(openssl_cipher_iv_length('AES-256-ECB'));
    $secret_iv = bin2hex($secret_iv1);
    $key = hash('sha256', $secret_key);    
    $iv = substr(hash('sha256', $secret_iv), 0, 16);

    $output = base64_encode(openssl_encrypt($string, 'aes-256-ecb', $key, OPENSSL_RAW_DATA));

I want decrypted output as : "durhs-14767-w0163j1-89047" Thanks in advance for your reply.


回答1:


Saddly, you are on the wrong way.

Refer to :

http://php.net/manual/en/function.mcrypt-encrypt.php#117667

MCRYPT_RIJNDAEL_256 is not AES-256, it's a different variant of the Rijndael block cipher.

https://en.wikipedia.org/wiki/Advanced_Encryption_Standard

AES is a variant of Rijndael which has a fixed block size of 128 bits, and a key size of 128, 192, or 256 bits. By contrast, the Rijndael specification per se is specified with block and key sizes that may be any multiple of 32 bits, with a minimum of 128 and a maximum of 256 bits.

So you can not use OpenSSL's AES-256 to decrypt the MCrypt's output.

Some possible methods:

  1. Keep using mcrypt by PECL's mcrypt extension (luckily, it is still there), until you can replace the legacy data totally.

  2. Rewrite a correct RIJNDAEL-256 cipher in PHP.



来源:https://stackoverflow.com/questions/49997338/mcrypt-rijndael-256-to-openssl-aes-256-ecb-conversion

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