美文网首页
php 敏感数据 aes 加密

php 敏感数据 aes 加密

作者: 码农工号9527 | 来源:发表于2025-01-24 10:38 被阅读0次
<?php

$key = '123';
$plainText = '{"a":1}';

# 当options为OPENSSL_RAW_DATA、OPENSSL_NO_PADDING时,加密结果为乱码,为提高可读性和确保网络协议的兼容性,推荐使用 base64_encode
$base64PlainText = base64_encode($plainText);

$enData = Crypt::aesEncrypt($base64PlainText, $key, 0);
$deData = Crypt::aesDecrypt($enData, $key, 0);

var_dump("加密原数据:$plainText");
var_dump("加密原数据(base64encode):$base64PlainText");
var_dump("加密后数据:$enData");
var_dump("解密后数据:$deData");
var_dump("解密后数据(base64decode):". base64_decode($deData));

class Crypt
{

    public static function aesEncrypt(string $plaintext, $key,int $options = OPENSSL_RAW_DATA): string
    {
        if (strlen($plaintext) == 0) {
            return '';
        }
        $key = md5($key);
        $cipher = 'AES-256-CBC';
        $ivLen = openssl_cipher_iv_length($cipher);
        $iv = openssl_random_pseudo_bytes($ivLen);
        $enData = openssl_encrypt($plaintext, $cipher, $key, $options, $iv);
        return base64_encode($iv . $enData);
    }

    public static function aesDecrypt(string $cryptoText, $key,int $options = OPENSSL_RAW_DATA): string
    {
        $cipher = 'AES-256-CBC';
        $ivLen = openssl_cipher_iv_length($cipher);
        $enData = base64_decode($cryptoText);
        if ($enData === false) {
            return '';
        }
        if (strlen($enData) <= $ivLen) {
            return '';
        }
        $key = md5($key);
        $iv = substr($enData, 0, $ivLen);
        return openssl_decrypt(substr($enData, $ivLen), $cipher, $key, $options, $iv);
    }
}

?>

相关文章

网友评论

      本文标题:php 敏感数据 aes 加密

      本文链接:https://www.haomeiwen.com/subject/srmcujtx.html