使用openssl_encrypt自己生成license.lic文件

发布时间 2023-09-28 10:59:59作者: 亚索会代码

 

    //生成加密文件
    public function createLicense()
    {
        // 加密信息
        $licenseData = [
            'user' => 'John Doe',
            'expiry' => '2022-12-31',
        ];
        $licenseData = json_encode($licenseData);//生成json

        $ivlen = openssl_cipher_iv_length("AES-256-CBC");//获得iv长度
        // 生成iv  16个字符串
        $iv = openssl_random_pseudo_bytes($ivlen);
        $encryptedContent = openssl_encrypt($licenseData, 'AES-256-CBC', "SAC-1", 0, $iv);//生成加密后的数据,64个字符串
        //必须携带原有iv
        $encryptedData = $iv . $encryptedContent;
        // 将授权文件写入磁盘
        return file_put_contents('you_path/license.lic', $encryptedData);
    }
    
    //读取加密信息
    public function readLicense(){
        //获取信息内容
        $encryptedContent = file_get_contents("you_path/license.lic");
        //读取前面16个字符加密的iv
        $iv = substr($encryptedContent, 0, 16);
        //获取16字符之后的数据
        $encryptedContent = substr($encryptedContent, 16);

        // 使用相同的加密算法和密钥对文件内容进行解密
        $decryptedContent = openssl_decrypt($encryptedContent, 'AES-256-CBC', "SAC-1", 0,$iv);
        return $decryptedContent;
    }