PHP 加密解密 AES-256-CBC-Pkcs7Padding

1,065 阅读1分钟

本文内容参考源链接:
AES-128-CBC-Pkcs7Padding加密PHP实例-腾讯云开发者社区-腾讯云 (tencent.com)

PHP可用的加密算法:
PHP: openssl_get_cipher_methods - Manual

本篇使用的是 'AES-256-CBC'。

如果是用Java或其它语言进行加密解密,然后使用PHP进行反向解密加密时,需要注意双方使用的加密算法是一样的。

代码如下:

<?php

class EncryptUtil
{
    protected $cipher_algo;
    protected $key; // 32位
    protected $iv; // 16位

    /**
     * 加密
     */
    public function encrypt($data): string
    {
        if (is_array($data)) {
            $data = json_encode($data);
        }
        $cipher_algo = $this->getCipherAlgo();
        $key = $this->getkey();
        $iv = $this->getiv();
        return base64_encode(openssl_encrypt($data, $cipher_algo, $key, OPENSSL_RAW_DATA, $iv));
    }

    /**
     * 解密
     */
    public function decrypt($data): string
    {
        $cipher_algo = $this->getCipherAlgo();
        $key = $this->getkey();
        $iv = $this->getiv();
        return openssl_decrypt(base64_decode($data), $cipher_algo, $key, OPENSSL_RAW_DATA, $iv);
    }

    public function setCipherAlgo(string $cipher_algo)
    {
        $this->cipher_algo = $cipher_algo;
        return $this;
    }

    public function setkey(string $key)
    {
        $this->key = $key;
        return $this;
    }

    public function setIv(string $iv)
    {
        $this->iv = $iv;
        return $this;
    }

    public function getCipherAlgo(): string
    {
        return $this->cipher_algo;
    }

    public function getkey(): string
    {
        return $this->key;
    }

    public function getiv(): string
    {
        return $this->iv;
    }

}

$encryptUtil = new EncryptUtil;

$encryptUtil->setCipherAlgo("AES-256-CBC");
$encryptUtil->setkey("12345678901234567890123456789012");
$encryptUtil->setIv("1234567890123456");

$s = "hello world";
echo (sprintf("加密前字符串 [%s]\n", $s));

$encrypted = $encryptUtil->encrypt($s);
echo (sprintf("加密结果 [%s]\n", $encrypted));

$decrypted = $encryptUtil->decrypt("4MfPVKPCpqIlK9VOqf2N9w==");
echo (sprintf("解密结果 [%s]\n", $decrypted));
echo "==============================";
?>

运行过程中碰到了下面的错误,在网上找了一圈,给出的方法都没能解决,安装了php 8 解决了。

Call to undefined function openssl_decrypt()