需求,对接接口,对方的内容是经过过 aes256 加密的,我们需要解密获得明文。我使用的版本为php5.6
首先加解密类:
<?php
/**
* php Aess_256 加解密类
*/
namespace Common\Lib;
class Aes256
{
/**
* Encrypt string
*
* @param string|numeric $text
* @param string $passphrase
* @return string
* @throws \Exception
*/
public static function encrypt($text, $passphrase)
{
$salt = openssl_random_pseudo_bytes(8);
$salted = $dx = '';
while (strlen($salted) < 48) {
$dx = md5($dx . $passphrase . $salt, true);
$salted .= $dx;
}
$key = substr($salted, 0, 32);
$iv = substr($salted, 32, 16);
// encrypt with PKCS7 padding
return base64_encode('Salted__' . $salt . openssl_encrypt($text . '', 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv));
}
/**
* Decrypt string
*
* @param string $encrypted
* @param string $passphrase
* @return string|numeric
* @throws \Exception
*/
public static function decrypt($encrypted, $passphrase)
{
$encrypted = base64_decode($encrypted);
$salted = substr($encrypted, 0, 8) == 'Salted__';
if (!$salted) {
return null;
}
$salt = substr($encrypted, 8, 8);
$encrypted = substr($encrypted, 16);
$salted = $dx = '';
while (strlen($salted) < 48) {
$dx = md5($dx . $passphrase . $salt, true);
$salted .= $dx;
}
$key = substr($salted, 0, 32);
$iv = substr($salted, 32, 16);
return openssl_decrypt($encrypted, 'aes-256-cbc', $key, true, $iv);
}
}
使用:解密。注:我对接别人的接口,明确说明 密文 和 密码 是需要先 base64_decode 一下的。自己使用的时候,需要看清下是否需要 这一步。实际上是没有这一步的。
// $cipherText 密文,这里看是否需要base64_decode,我对接的接口是需要先base64_decode一下的。
// $this->key 双方规定的密码,这里看是否需要base64_decode,我对接的接口是需要先base64_decode一下的
$aesData = Aes256::decrypt(base64_decode($cipherText), base64_decode($this->key));
参考地址:
https://shannonai.feishu.cn/docs/doccnq5BSI6GOQtzWiiRhjwpjRc#1LPO1b
https://github.com/SHANNON-AI/Aifun-Sdk-Example
以上就是php7.1以下加解密。测试过并已经成功。
以下是php7.1以上的版本,但没有测试过:
// php7.1以上
$cipher = "aes-128-gcm";
$key = hex2bin($this->secretKey);
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$encrypt = openssl_encrypt($data, $cipher, $key, OPENSSL_RAW_DATA, $iv, $tag);
return base64_encode(($iv . $encrypt . $tag));