<?php /** * 对数据进行签名 * $data = "This is site php3.cn"; 签名数据 * $privatekeyFile = "/path/to/private.key"; 私钥 * $passphrase = ; 密码 */ function sign($data, $privatekeyFile, $passphrase) { // 加载私钥 $privatekey = openssl_pkey_get_private(file_get_contents($privatekeyFile), $passphrase); $algo = OPENSSL_ALGO_SHA1; //签名算法 openssl_sign($data, $signature, $privatekey, $algo); openssl_free_key($privatekey);//释放内存 return base64_encode($signature); } /** * 验签 * $data = "This is site php3.cn"; * $publickeyFile = "/path/to/public.key"; 公钥 */ function verify($data, $signature, $publickeyFile) { $algo = OPENSSL_ALGO_SHA1;// 签名的算法,同上面一致 $publickey = openssl_pkey_get_public(file_get_contents($publickeyFile));// 加载公钥 // 验签 $verify = openssl_verify($data, base64_decode($signature), $publickey, $algo); openssl_free_key($publickey); return $verify; // int(1)表示验签成功 } /** * 加密 * $data = "This is site php3.cn"; * $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一致 }