openssl:php利用openssl实现RSA非对称加密签名

php利用openssl实现RSA非对称加密签名

1. 先用php生成一对公钥和私钥

$res = openssl_pkey_new();
openssl_pkey_export($res,$pri);
$d= openssl_pkey_get_details($res);
$pub = $d[‘key’];
var_dump($pri,$pub);

2. 保存好自己的私钥,把公钥可以公开给别人。如果需要对某数据进行签名,证明那数据是从你这里发出的,就需要用私钥:

$res = openssl_pkey_get_private($pri);
if (openssl_sign(‘hello’, $out, $res))
var_dump(base64_encode($out));

上例中 $pri 为自己的私钥,’hello’ 为待签名的数据,如果签名成功,最后输出为base64编码后的签名,如:

j19H+C/NQEcyowezOQ+gmGi2UoPJNXyJ+KwpkEzJ5u4qaRD3cY4qhfFfIosypypwJT
J4LjRYOIPNQMQm6ICj2nMdGfn/p/pp7il+xGz2aUWdOXkJFgIc/PGC95C9sLH04Tc6
QSuV5IMd9rjBjyv+ieokMLFm9cmtN2hGag9vq1s=

3. 别人收到你的数据 ‘hello’ 和签名字串,想验证这是从你发来的数据的话,用你公开的公钥验证:

$sig = base64_decode($sig);
$res = openssl_pkey_get_public($pubkey);
if (openssl_verify(‘hello’, $sig, $res) === 1)
; // 通过验证

上例中刚开始的 $sig 为之前你base64编码过的签名, $pubkey 为你的公钥

以下为网易一卡通直通车的过程分析

<?php
// Rsa的公私钥
$pubkey =
‘—–BEGIN PUBLIC KEY—–
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCurS+gyXEGyNxKcu1Ja0L6uN7/
TBMNQw/DgicvftExXrus1zTPL5jSe/fOjAqssO52Pla0UlugIAgazYn/HLjEWvtg
Sjsqi65R+4FbC95BROKR1qhsAo2xb25EZ/Ab94khxlYBTtAfSFcT9dIXP6rmmW2w
SlnIOSSxLplfj7I4jQIDAQAB
—–END PUBLIC KEY—–
‘;
$prikey =
‘—–BEGIN RSA PRIVATE KEY—–
MIICXAIBAAKBgQDWglpJUgBrlolNz4cgRBxsD/Em8N+5g/IyFuEj0DqRG8jN8CIA
l8W/zdsPn8YBqaml9ovtySHhk2sRYWCGPTebFcS5EIrMJHtQaIv6VoaEI6hSfreK
RZ73/tMOoKivKwNBRKSLewhXdq5pc4sc00as4CrxDi1yPOk+ROyONCom9QIDAQAB
AoGAX0vbxnT6oNFowDuxAUGhCtTuQmmCSs12fJAzhxCL5ElepTbINFE41eQjLMbD
VZvFNWjZc1MGjUtLppYHJrvthlRw2dRHHd1adwy1TB1aPKvgkr/78a7YwQJrMl/1
/eIs7Ry/DqZatRCqeK0TTW6A+rlwmvtvJ2dO+mgO1DUWUwECQQD+kLSVcxqDAKY7
gyhlzDAfYQgdva4+jP1a2vXDP6A+9m7uEP/yRmUO9O/jsoE8s29ujBq6XnYA2KI8
vedny6NBAkEA17faaBMKkKNhWmSeHD+raBLc4xElQVXysvw7RPfBtjSEqouaDCBg
g1r1e054Pj+pyLWdjW0P7R7Y8FWVWHM6tQJAPKs6DoAfKmeGNpq8jv5J3cCfUY86
LrglTXjvp3fLdhX/PAebKB90yErBvU92k4PkI8GKQS5wCyWWDMnpk4gpwQJABUUP
h9VXP7tOCIhGuIfxpwQ28zEbCOKRoD+7Lu8ig1H7H7NzWvJ7iRnyv0VmeJbTjfyp
0aelaPSE9jIRCO0ftQJBAKTyfoe6v6WjRmSQql2CVMCJ/0SyAjduJyzJDBLPgs+V
i0s+73mVYJihdjkA9chHKJwqJ0JIMvxUXNt2VTgwUVE=
—–END RSA PRIVATE KEY—–
‘;

$site_id=”95184″;
$order_id=”123″;
$order_time=”20120307120000″;
$user_id=”61981700″;
$urs=”someone@163.com”;
$reason=”1″;
$pts=”150″;

$sign=$site_id.””.$user_id.””.$order_id.””.$order_time.””.$urs.””.$reason.””.$pts;

$sign=sha1($sign);

$res = openssl_pkey_get_private($prikey);

if (openssl_sign($sign, $out, $res))
$sign=bin2hex($out);

$url=”http://esalesdev.163.com:8002/script/interface/dc_input?site_id=”.$site_id.”&order_id=”.$order_id.”&order_time=”.$order_time.”&user_id=”.$user_id.”&urs=”.$urs.”&reason=”.$reason.”&pts=”.$pts.”&sign=”.$sign;
print_r($url);

?>
Tags:,
179 Comments

Add a Comment

邮箱地址不会被公开。 必填项已用*标注