| ????????最近在项目中需要对用户信息进行加密,因为这个项目还需要对加密的信息进行解密,所以不打算采用md5进行加密。在网上找了市面上常用的对称加密算法后,发现Aes算法比较推荐使用,所以最后选定了使用Aes。在使用Aes的过程中遇到了字符串被截断的问题,最后解决了,将经验分享出来记录一下。 ? ? ? ? 我的问题是部分数据经过Aes加密后出现了/斜杠符号,由于使用的是thinkphp框架,而且tp的参数都是使用/斜杠进行分隔的,所以导致在将含有/斜杠符号的加密数据进行拼接的时候导致数据被截断,百度后无意中发现了php有一个将字符串转为16进制的方法:bin2hex($str),尝试了之后发现有效 代码如下: $plainText = '7tXkOG1uTESIzhR6';  // 要加密的数据
$aes = new Aes('key');  // 实例化Aes类,并传递密钥key
// 加密   BFneJm/SGOU8qT4gUhOuDccXUw9B8yB1e0qhv68RxC4=
$cipherText = $aes->encrypt($plainText);
// 此时密文中含有/符号,不能直接传输,否则将无法正常传递回来,需要再对密文进行编码为16进制的字符串
$hexText = bin2hex($cipher);  // 将字符串编码为16进制的字符串 
// 42466e654a6d2f53474f55387154346755684f7544636358557739423879423165307168763638527843343d
 可以看到此时就已经没有/符号了,可以放心拿来传输了 需要解密的时候再将16进制值转换回来就好了: $aes = new Aes('key');
// 加密数据的16进制数据
$cipherText = '42466e654a6d2f53474f55387154346755684f7544636358557739423879423165307168763638527843343d';
$plainText = hex2bin($cipherText); // 将16进制值转换位二进制字符串  7tXkOG1uTESIzhR6
 到这里就结束了。 最后再附上我使用的封装好的Aes类,也是我在网上找的别人分享的资源 <?php
/**
 * Aes 对称加密
 * Class Aes
 * @package app\admin\model
 */
class Aes
{
    /**
     * var string $method 加解密方法,可通过openssl_get_cipher_methods()获得
     */
    protected $method;
    /**
     * var string $secret_key 加解密的密钥
     */
    protected $secret_key;
    /**
     * var string $iv 加解密的向量,有些方法需要设置比如CBC
     */
    protected $iv;
    /**
     * var string $options (不知道怎么解释,目前设置为0没什么问题)
     */
    protected $options;
    /**
     * 构造函数
     *
     * @param string $key 密钥
     * @param string $method 加密方式
     * @param string $iv iv向量
     * @param mixed $options 还不是很清楚
     *
     */
    public function __construct($key, $method = 'AES-128-ECB', $iv = '', $options = 0)
    {
        // key是必须要设置的
        $this->secret_key = isset($key) ? $key : 'morefun';
        $this->method = $method;
        $this->iv = $iv;
        $this->options = $options;
    }
    /**
     * 加密方法,对数据进行加密,返回加密后的数据
     *
     * @param string $data 要加密的数据
     *
     * @return string
     *
     */
    public function encrypt($data)
    {
        return openssl_encrypt($data, $this->method, $this->secret_key, $this->options, $this->iv);
    }
    /**
     * 解密方法,对数据进行解密,返回解密后的数据
     *
     * @param string $data 要解密的数据
     *
     * @return string
     *
     */
    public function decrypt($data)
    {
        return openssl_decrypt($data, $this->method, $this->secret_key, $this->options, $this->iv);
    }
}
 官方方法参考文档: bin2hex():https://www.php.net/manual/zh/function.bin2hex.php hex2bin():https://www.php.net/manual/zh/function.hex2bin.php |