学会用PHP的openssl扩展

1、先用openssl_pkey_new()函数产生一个私钥pri_key

$dn = array(
    "countryName" => "UK",
    "stateOrProvinceName" => "Somerset",
    "localityName" => "Glastonbury",
    "organizationName" => "The Brain Room Limited",
    "organizationalUnitName" => "PHP Documentation Team",
    "commonName" => "Wez Furlong",
    "emailAddress" => "wez@example.com"
);

// Generate a new private (and public) key pair
$privkey = openssl_pkey_new();

2、用openssl_csr_new()函数以私钥pri_key 产生一个信用证csr

// Generate a certificate signing request
$csr = openssl_csr_new($dn, $privkey);

3、用openssl_sign()函数以私钥pri_key对一段数据data产生一个数字签名signature

// $data is assumed to contain the data to be signed

// fetch private key from file and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r");
$priv_key = fread($fp, 8192);
fclose($fp);
$pkeyid = openssl_get_privatekey($priv_key);

// compute signature
openssl_sign($data, $signature, $pkeyid);

// free the key from memory
openssl_free_key($pkeyid);

4、用openssl_pkey_get_public()函数从信用证csr中获得公钥pub_key

$res = openssl_pkey_get_public($key);

5、把公钥pub_key、数字签名signature、数据data发给对方。
6、对方收到3项后,用openssl_verify()函数或其他验证工具,验证签名。

// $data and $signature are assumed to contain the data and the signature

// fetch public key from certificate and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pubkeyid = openssl_get_publickey($cert);

// state whether signature is okay or not
$ok = openssl_verify($data, $signature, $pubkeyid);
if ($ok == 1) {
    echo "good";
} elseif ($ok == 0) {
    echo "bad";
} else {
    echo "ugly, error checking signature";
}
// free the key from memory
openssl_free_key($pubkeyid);

7、对方验证有效,开始使用你的信息data。验证无效,再找你扯皮。

发表评论

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