AES-256-CBC只是其中一个加密长度,可换其他

字符串加密

function aesEncrypt( $plaintext )
    {
        $key = "123456789";//关键密钥
        $cipher = "AES-256-CBC";

        $ivlen = openssl_cipher_iv_length( $cipher );
        $iv = openssl_random_pseudo_bytes( $ivlen );
        $ciphertext_raw = openssl_encrypt( $plaintext, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv );
        if( openssl_error_string () )
            return false;
        
        $ciphertext = base64_encode( $iv.$ciphertext_raw );

        return $ciphertext;
    }

    //字符串解密
    function aesDecrypt( $ciphertext )
    {
        $key = "123456789";//关键密钥
        $cipher = "AES-256-CBC";

        $c = base64_decode( $ciphertext );
        $ivlen = openssl_cipher_iv_length( $cipher );
        $iv = substr( $c, 0, $ivlen );
        $ciphertext_raw = substr( $c, $ivlen );
        $plaintext = openssl_decrypt( $ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv );
        if( openssl_error_string () )
            return false;
        
        return $plaintext;
    }

点赞(0)
发表
评论
返回
顶部