PHP头条
热点:

php AES加密解密示例


php AES 加密解密示例。

<?php

/**
 * Created by PhpStorm.
 * User: yhm
 * Date: 20-1-10
 * Time: 上午10:12
 */

define('ENCODE_KEY', 'phpernote.com');

class AES {
    //AES-128-CBC 加密算法。openssl_get_cipher_methods() 可获取有效密码方式列表。
    /**
     * 参数说明:
     * $data: 加密明文
     * $method: 加密方法
     * $passwd: 加密密钥
     * $iv: 加密初始化向量(可选)
     */
    public static function encrypt($string, $key, $iv) {
        $data = @openssl_encrypt($string, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
        $data = strtolower(bin2hex($data));
        return $data;
    }

    /**
     * 参数说明:
     * $data: 解密密文
     * $method: 解密加密方法
     * $passwd: 解密密钥
     * $iv: 解密初始化向量(可选)
     */
    public static function decrypt($string, $key, $iv) {
        $decrypted = @openssl_decrypt(hex2bin($string), 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
        return $decrypted;
    }
}

/**
 * 加密
 * @param string $string
 * @return string
 */
function encode($string) {
    if (!$string) {
        return '';
    }

    return trim(base64_encode(AES::encrypt(base64_encode(urlencode($string)), ENCODE_KEY, md5(ENCODE_KEY, true))));
}

/**
 * 解密
 * @param string $string
 * @return string
 */
function decode($string) {
    if (!$string) {
        return '';
    }

    return trim(urldecode(base64_decode(AES::decrypt(base64_decode($string), ENCODE_KEY, md5(ENCODE_KEY, true)))));
}

www.phpzy.comtrue/php/40728.htmlTechArticlephp AES加密解密示例 php AES 加密解密示例。 ?php/** * Created by PhpStorm. * User: yhm * Date: 20-1-10 * Time: 上午10:12 */define('ENCODE_KEY', 'phpernote.com');class AES { //AES-128-CBC 加密算法。openssl_get_cipher_metho...

相关文章

PHP之友评论

今天推荐