/** * 對數據進行簽名 * $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一致 }