对称加密使用秘钥加、解密数据,需要双方约定同一个秘钥,一旦约定过程中出现泄漏那么加密信息也就不安全了,但是它有加、解密快的特点。

aes算法 cbc模式 PKCS5Padding补码方式

与java加解密结果一致,代码如下:

<?php
class Aes
{

    private $iv = "";//iv的长度要根据加密方式和模式来定,aes-128-cbc偏移量的是16位

    private $key = ''; 

    function __construct($key, $iv)
    {
        $this->key = $key;
        $this->iv = $iv;
    }


    public function encrypt($input)
    {
        return base64_encode(openssl_encrypt($input, 'AES-128-CBC', $this->key, OPENSSL_RAW_DATA, $this->iv));
    }

    public function decrypt($input)
    {
       return openssl_decrypt(base64_decode($input), 'AES-128-CBC', $this->key, OPENSSL_RAW_DATA, $this->iv);
    }

}

下面是使用php openssl_encrypt加密的通用方法,摘自https://www.php/manual/zh/function.openssl-encrypt.php:

<?php
$plaintext = "message to be encrypted";//加密字符串
$cipher = "aes-128-gcm";//加密方式
if (in_array($cipher, openssl_get_cipher_methods()))//是否支持改加密方式
{
    $ivlen = openssl_cipher_iv_length($cipher);//向量长度
    $iv = openssl_random_pseudo_bytes($ivlen);//创建指定长度的向量
    $ciphertext = openssl_encrypt($plaintext, $cipher, $key, $options=0, $iv);
    $original_plaintext = openssl_decrypt($ciphertext, $cipher, $key, $options=0, $iv);
    echo $original_plaintext."\n";
}
?>

 

更多推荐

PHP使用openssl_encrypt进行aes对称加密AES/CBC/PKCS5Padding与JAVA互通