PHP中AES加/解密

加密

$plaintext = trim($plaintext);
if ($plaintext === '') return '';

$method = 'AES-128-CBC';
$ivlen = openssl_cipher_iv_length($method);
$iv = str_repeat("\0", $ivlen); // 使用16个字节的初始化向量

// 对密钥长度进行调整,AES-128需要16字节的密钥
$key = substr($key, 0, 16);

// 使用OpenSSL进行加密,注意PKCS7Padding是默认的,无需手动添加
$encrypted = openssl_encrypt($plaintext, $method, $key, OPENSSL_RAW_DATA, $iv);

return base64_encode($encrypted);

解密

public static function AesDecrypt($encrypted, $key = null)
    {
        if ($encrypted == '') return '';
        $cipher = "aes-128-cbc";
        if (!in_array($cipher, openssl_get_cipher_methods())) {
            throw new Exception("不支持的加密方法: " . $cipher);
        }
        $ciphertext_dec = base64_decode($encrypted);

        // OpenSSL expects a key of 16, 24 or 32 bytes length
        // depending on the cipher and mode
        #$key = self::mbSubstr($key, 0, 32); // AES-256 uses 32 bytes
        #这里是关键 
        $key = base64_decode($key);
        // OpenSSL expects an IV of 16 bytes
        $iv = str_repeat("\0", 16);

        // OpenSSL uses the same key for encryption and decryption
        $decrypted = openssl_decrypt(
            $ciphertext_dec,
            'AES-128-CBC', // Use AES-128-CBC as an example
            $key,
            OPENSSL_RAW_DATA, // Flag to return the raw data
            $iv
        );

        // No need to rtrim() as openssl_decrypt() doesn't pad with null bytes
        // $a = rtrim($decrypted, "\0"); // This line is not needed

        // Ensure the decrypted text is not empty and return
        return $decrypted ?? '';
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值