使用openssl_encrypt()和openssl_decrypt()实现加密和解密功能

<?php
declare(strict_types=1);
ini_set('display_errors', 'On');
ini_set('error_reporting', E_ALL);

use Random\RandomException;

/**
 * 加密解密类
 */
class Cipher
{
    /**
     * @var string 加密算法
     */
    private static string $algo = 'AES-256-GCM';

    /**
     * 加密方法
     *
     * @param string $plaintext 明文
     * @return string|false 加密后的密文,若加密失败则返回false
     */
    public static function encrypt(string $plaintext): string|false
    {
        try {
            $iv = random_bytes(12);
        } catch (RandomException) {
            $iv = false;
        }

        if (is_string($iv)) {
            $ciphertext = openssl_encrypt($plaintext, static::$algo, static::getKey(), OPENSSL_RAW_DATA, $iv, $tag);
            if (is_string($ciphertext)) {
                $ciphertext = base64_encode($iv . $tag . $ciphertext);
            }
        }

        return (isset($ciphertext) && is_string($ciphertext)) ? $ciphertext : false;
    }

    /**
     * 解密方法
     *
     * @param string $ciphertext 密文
     * @return string|false 解密后的明文,若解密失败则返回false
     */
    public static function decrypt(string $ciphertext): string|false
    {
        $decode = base64_decode($ciphertext);
        if (is_string($decode)) {
            $iv = substr($decode, 0, 12);
            $tag = substr($decode, 12, 16);
            $data = substr($decode, 28);
            $plaintext = openssl_decrypt($data, static::$algo, static::getKey(), OPENSSL_RAW_DATA, $iv, $tag);
        }

        return (isset($plaintext) && is_string($plaintext)) ? $plaintext : false;
    }

    /**
     * 获取密钥
     *
     * @return string 密钥
     */
    private static function getKey(): string
    {
        $key = 'www.manong.life'; // 密钥(这里假设从配置文件或别的地方里获取到了密钥)

        return md5($key); // 密钥长度必须是32位,故这里使用md5()处理一下以确保满足长度要求
    }

}

$encrypt = Cipher::encrypt('PHP是世界上最好の语言');

echo "加密结果:$encrypt" . PHP_EOL; // 加密结果:boj+mOS05iG6lGH7RGB1cRtz……

$plaintext = Cipher::decrypt($encrypt); // 解密结果:PHP是世界上最好の语言

echo "解密结果:$plaintext" . PHP_EOL;

Copyright © 2025 码农人生. All Rights Reserved