由于http请求是无状态,所以我们不知道请求方到底是谁。于是就诞生了签名,接收方和请求方协商一种签名方式进行验证,来取得互相信任,进行下一步业务逻辑交流。
其中签名用得很多的就是公钥私钥,用私钥签名,公钥验签,或者公钥加密,私钥解密。
不管是公钥和私钥,我们首先要进行格式化,当然如果你获取的就是格式化后的可忽略这一步
1、公钥私钥的格式化
********************私钥格式化********************/ function formatPriKey($priKey) { $fKey = "-----BEGIN PRIVATE KEY----- "; $len = strlen($priKey); for($i = 0; $i < $len; ) { $fKey = $fKey . substr($priKey, $i, 64) . " "; $i += 64; } $fKey .= "-----END PRIVATE KEY-----"; return $fKey; } /********************公钥格式化********************/ function formatPubKey($pubKey) { $fKey = "-----BEGIN PUBLIC KEY----- "; $len = strlen($pubKey); for($i = 0; $i < $len; ) { $fKey = $fKey . substr($pubKey, $i, 64) . " "; $i += 64; } $fKey .= "-----END PUBLIC KEY-----"; return $fKey; }
格式化也就是加上前后缀,然后每64位进行换行,还可如下简单格式化:
//私钥格式化 $fKey = "-----BEGIN PRIVATE KEY----- ".chunk_split($public_key, 64," ").'-----END PRIVATE KEY-----'; //公钥格式化 $fKey = "-----BEGIN PUBLIC KEY----- ".chunk_split($public_key, 64," ").'-----END PUBLIC KEY-----';
2、私钥签名和公钥验签(SHA1withRSA)
/********************私钥签名********************/ function get_private_sign($sign_str,$private_key,$signature_alg=OPENSSL_ALGO_SHA1){ $private_key = openssl_pkey_get_private(private_key);//加载密钥 openssl_sign($sign_str,$signature,$private_key,$signature_alg);//生成签名 $signature = base64_encode($signature); openssl_free_key($private_key); return $signature; } /********************公钥验签********************/ function public_verify($sign_str,$sign,$public_key,$signature_alg=OPENSSL_ALGO_SHA1){ $public_key = openssl_get_publickey($public_key); $verify = openssl_verify($sign_str, base64_decode($sign), $public_key, $signature_alg); openssl_free_key($public_key); return $verify==1;//false or true }
$sign_str为签名字符串或者验签字符串,$sign为签名,公钥私钥都必须是格式化后的,否则会无法识别。
3、公钥加密和私钥解密(SHA1withRSA)
/********************公钥加密********************/ function get_public_sign($sign_str,$public_key,$signature_alg=OPENSSL_ALGO_SHA1){ $public_key = openssl_pkey_get_public($public_key);//加载密钥 openssl_sign($sign_str,$signature,$public_key,$signature_alg);//生成签名 $signature = base64_encode($signature); openssl_free_key($public); return $signature; } /********************私钥解密********************/ function private_verify($sign_str,$sign,$private_key,$signature_alg=OPENSSL_ALGO_SHA1){ $private_key = openssl_get_privatekey($private_key); $verify = openssl_verify($sign_str, base64_decode($sign), $private_key, $signature_alg); openssl_free_key($private_key); return $verify==1;//false or true }
4、AES(AES/ECB/PKCS5Padding)加密解密
//aes加密 function encrypt($data, $key) { $data = openssl_encrypt($data, 'aes-128-ecb', base64_decode($key), OPENSSL_RAW_DATA); return base64_encode($data); } //aes解密 function decrypt($data, $key) { $encrypted = base64_decode($data); return openssl_decrypt($encrypted, 'aes-128-ecb', base64_decode($key), OPENSSL_RAW_DATA); }