PHP 之用证书对数据进行签名、验签、加密、解密

    /**
    *    对数据进行签名
    *    $data = 'If you are still new to things, we’ve provided a few walkthroughs to get you started.'; 签名数据
    *    $privatekeyFile = '/path/to/private.key'; 私钥
    *    $passphrase = ''; 密码
    */
    function sign($data, $privatekeyFile, $passphrase) 
    {
        // 摘要及签名的算法
        $digestAlgo = 'sha512';
        $algo = OPENSSL_ALGO_SHA1;
        // 加载私钥
        $privatekey = openssl_pkey_get_private(file_get_contents($privatekeyFile), $passphrase);
        // 生成摘要
        $digest = openssl_digest($data, $digestAlgo);
        // 签名
        $signature = '';
        openssl_sign($digest, $signature, $privatekey, $algo);
        //释放内存
        openssl_free_key($privatekey);
        $signature = base64_encode($signature);
         return $signature;
    }

    /**
    *    验签
    *    $data = 'If you are still new to things, we’ve provided a few walkthroughs to get you started.';
    *    $publickeyFile = '/path/to/public.key'; 公钥
    */
    function verify($data, $publickeyFile) 
    {
        // 摘要及签名的算法,同上面一致
        $digestAlgo = 'sha512';
        $algo = OPENSSL_ALGO_SHA1;
        // 加载公钥
        $publickey = openssl_pkey_get_public(file_get_contents($publickeyFile));
        // 生成摘要
        $digest = openssl_digest($data, $digestAlgo);
        // 验签
        $verify = openssl_verify($digest, base64_decode($signature), $publickey, $algo);
        openssl_free_key($publickey);
        return $verify; // int(1)表示验签成功
    }
    /**
    *    加密
    *    $data = 'If you are still new to things, we’ve provided a few walkthroughs to get you started.';
    *    $publickeyFile = '/path/to/public.key'; 公钥
    */
    function encrypt($data, $publickeyFile)
    {
        // 加载公钥
        $publickey = openssl_pkey_get_public(file_get_contents($publickeyFile));
        // 使用公钥进行加密
        $encryptedData = '';
        openssl_public_encrypt($data, $encryptedData, $publickey);
        return base64_encode($encryptedData);
    }
    /**
    *    解密
    *    $encryptedData 待解密数据
    *    $privatekeyFile = '/path/to/private.key'; 私钥
    *    $passphrase = ''; 密码
    */
    function decrypt($encryptedData, $privatekeyFile, $passphrase)
    {
        // 加载私钥
        $privatekey = openssl_pkey_get_private(file_get_contents($privatekeyFile), $passphrase);
        // 使用公钥进行加密
        $sensitiveData = '';
        openssl_private_decrypt(base64_decode($encryptedData), $sensitiveData, $privatekey);
        return $sensitiveData; // 应该跟$data一致
    }    

 

posted @ 2019-01-28 22:08  样子2018  阅读(1769)  评论(0编辑  收藏  举报