1 代码与说明

  • 说明

    • IV: 向量,在下面的模式下为 16 字长字符串,UTF8 编码,128 位
    • KEY: 密钥,16 字长字符串,UTF8 编码,128 位
    • BLOCK: 128
    • MODE: CBC
    • PADDING: PKCS5/PKCS7, 在验证网站上测试,没发现区别
    • 加密结果以 Base64 方式编码
  • 代码

    class AESHelp {
        private $iv;
        private $key;
        private $method = 'AES-128-CBC';
    
        function __construct($iv, $key) {
            $this->iv = $iv;
    
            $ivLength = openssl_cipher_iv_length($this->method);
            if (strlen($this->iv) < $ivLength) {
                throw new Exception("iv less than {$ivLength}");
            }
    
            $this->key = $key;
        }
    
        function encrypt($data) {
            return base64_encode(openssl_encrypt($data, $this->method, $this->key, $options = OPENSSL_RAW_DATA, $this->iv));
        }
    
        function decrypt($data) {
            return openssl_decrypt(base64_decode($data), $this->method, $this->key, $options = OPENSSL_RAW_DATA, $this->iv);
        }
    }
    

2 示例

$iv = 'a123456789012345';
$key = 'hello';
$aes = new AESHelp($iv, $key);

$str1 = $aes->encrypt('123456');
echo "str1: {$str1} <br>";  // 输出: kkO6XPGyof3DQLSunkeTuA==

$str2 = $aes->decrypt($str1);
echo "str2: {$str2} <br>";  // 输出:123456