继上一篇RSA对传输信息进行加密解密,再写个生成签名和验证签名。
一般,安全考虑,比如接入支付平台时,请求方和接收方要互相验证是否是你,就用签名来看。
签名方式一般两种,对称加密和非对称加密。对称加密就是双方互相有一个相同的key。非对称比如就是公钥和私钥。
利用非对称openssl,下面是生成签名和验证签名的php示例。
<?php $arrParams = array( 'z' => 1, 'a' => 2, 'n' => "hello", 'p' => "你好", 'c' => 0, ); $sortStr = createString($arrParams);// 有序生成字符串 // echo $sortStr;die; $sha = sha1($sortStr);// sha1生成摘要 // echo $sha;die; $private_key = '-----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDKEquCt8WfdPFldkwy7GH3P274g4rxT2bFtaAlGKV03NVnZd/o 8+NvHyScilc4Awpp+xv0EJl25qI+OxoFjl0dGFXf8P4E93onPeZYfYtynTkhsFZv CFYuf0GQW8o7M16d7WDeOKhyf9G/RWWTYYHwFO0uIPDXEgDHfLzf4NsZsQIDAQAB AoGAUyLZQ19+Q/tl8Xt5IB5Ws9V6P25HNL6ZJtBxwbFhKTJN7ktgksP8l1Q1yN21 woqltzKjrodBzERZDcddDloi/kFCSj0I5rmnfMRifo8PLbv5+F9knxAyBc8Na52w JLyv5+vqJM5cJ5OBxX055ipssQxBgno7OVJCgP8dY/EGnW0CQQDl9No8cmr3tha0 I9KPHbibwrwT9THBB5oGu3PUqTlBuJixjxGgf0pUm+qHw/r3PG1jNqD9Xx5REoQN RrfQgLdPAkEA4PVjU8361m8weCUkm4jh/rsa8VYsiDEGCKEM6vmtaBYRlAXSeeb2 P/2MNlwI9bMSjiQ0q/XftHdSz4N+5/Le/wJBALDGBW4qVuiN5e4dC6RRKLU0gfil qNXGzjUWrPhyDj3jdh4o6VgEAlQAd85ebfLZVQ3L1P5xvJB+N10tW+jAyikCQQCm jAYlnXIAIAG6cYVQwV7PwKaJ1krR6bmV2eY+cOs5DF2nQUg6iAv4BDcyZ6EahqFO Ku/z/+zHJzBgAfKKtvzxAkBeT86uZ6tfTNLR72UbP0abWKfE65cTNHGQZKp3Df79 Gx+UKVNiDHnfYmUu412QbpqDqi95XTDiPnry0fGqlzVJ -----END RSA PRIVATE KEY-----';// 获取私钥 $pri_key_id = openssl_pkey_get_private($private_key);// 可用返回资源id Resource id //var_dump($pri_key_id);die; $re = openssl_sign($sha, $signature, $pri_key_id, OPENSSL_ALGO_SHA1); // var_dump($re);die; // $signature_base = base64_encode($signature); // 网络请求,post过去该base64字段,另一端解密 // echo $signature_base;die; // -----------------验签---------------- // 验签服务器拿到以上的参数(unset($signature)),同样生成有序串;sha1(); $public_key = '-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDKEquCt8WfdPFldkwy7GH3P274 g4rxT2bFtaAlGKV03NVnZd/o8+NvHyScilc4Awpp+xv0EJl25qI+OxoFjl0dGFXf 8P4E93onPeZYfYtynTkhsFZvCFYuf0GQW8o7M16d7WDeOKhyf9G/RWWTYYHwFO0u IPDXEgDHfLzf4NsZsQIDAQAB -----END PUBLIC KEY-----'; $pu_key = openssl_pkey_get_public($public_key); $verify = openssl_verify($sha, $signature, $pu_key, OPENSSL_ALGO_SHA1); if($verify == 1){ echo 'ok'; } else { echo 'fail'; } /** * @param $param * @return bool|string * 生成有序字符串 */ function createString($param){ if (!is_array($param) || empty($param)){ return false; } ksort($param); $concatStr = ''; foreach ($param as $k=>$v) { $concatStr .= $k.'='.$v.'&'; } $concatStr = rtrim($concatStr, '&'); return $concatStr; }