CHINA PHP CODER

CHINA PHP CODER

Who am I?

I am a china php coder.


What I write about


Recent Posts

php openssl实现aes加密

  php7.0版本开始mcrypt已经不再推荐使用,而php7.2版本开始mcrypt彻底被废弃并且被 OpenSSL 所取代,这里介绍一下如何使用openssl实现aes cbc方式加密,不再废话,直接上代码

  1. mcrypt方式加密代码
    function mcrypt_aes_cbc($data,$key,$iv='')
    {
    return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv));
    }
    $data = "123456";
    $key = "1234567890abcdef";
    $iv = "1234567890abcdef";
    echo mcrypt_aes_cbc($data,$key,$iv);
  2. opensssl方式加密代码
    function openssl_aes_cbc($data,$key,$iv='') {
    if( strlen($data) % 16 != 0 ) {
        $data .= str_repeat(chr(0), 16 - (strlen($data) % 16));
    }
    return base64_encode(openssl_encrypt($data, 'AES-128-CBC', $key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $iv ));
    }
    $data = "123456";
    $key = "1234567890abcdef";
    $iv = "1234567890abcdef";
    echo openssl_aes_cbc($data,$key,$iv);

    ※注意$key和$iv的长度为16位字符串。