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一致
    }    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM