PHP的SHA256WithRSA签名和验签

2020-3-19    elvin 随记

//生成 sha256WithRSA 签名
function getSign($content, $privateKey){
    $privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" .
        wordwrap($privateKey, 64, "\n", true) .
        "\n-----END RSA PRIVATE KEY-----";

    $key = openssl_get_privatekey($privateKey);
    openssl_sign($content, $signature, $key, "SHA256");
    openssl_free_key($key);
    $sign = base64_encode($signature);
    return $sign;
}

//验证 sha256WithRSA 签名
function verify($content, $sign, $publicKey){
    $publicKey = "-----BEGIN PUBLIC KEY-----\n" .
    wordwrap($publicKey, 64, "\n", true) .
    "\n-----END PUBLIC KEY-----";

    $key = openssl_get_publickey($publicKey);
    $ok = openssl_verify($content,base64_decode($sign), $key, 'SHA256');
    openssl_free_key($openssl_public_key);
    return $ok;
}

开启PHP的php_openssl扩展
生成公钥和密钥
<?php
header("Content-type:text/html;charset=utf-8");
$configargs = array('config'=>'\路径\openssl.cnf');   //路径
$res = openssl_pkey_new($configargs);
openssl_pkey_export($res,$pri, null, $configargs);
$d= openssl_pkey_get_details($res);
$pub = $d['key'];
var_dump($pri,$pub);
die;

标签: php SHA256WithRSA

发表评论