PHP使用Java生成RSA密钥对进行签名、验签

1、Java生成的密钥对(base64字符串)

String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJIQ+dgSAgEKAJ7Wf2fsztYQwmDBwZoVwmBDcm/SzdxAh8f3Oq3D5tghImj3fKATrLdoMZLETnVnoIVK+T014I8gICVoTmHNsyb3pp4r43W2NAcaL+YTB4WRVuCfye9QVOtBqRVK9e2Ltwjv0hea6iqBD4+w3Gbu8zWPcjRRt95BAgMBAAECgYEAgy/mBa8ex6ohJofGBCQHHPIOcnJzHJ4AZw8Mv+xYYkI+8VVWCW0SbvlLe3UUJH2nOU7Gf2f6g63f2PeeZOB33xkDoXTe+tVBjzIUKAwbwMvlMwtxPigAs2zMLBu1tMxovPmR3GM6JchF/vnMHu/zwH9ZvKouOy6idPZT3flY7UUCQQDBmQtIBwtI6TEhvZf8DorQ6A8Ng2pFpxkjZRAoyiMIphys8LuPphINy2IBCO9Hxgq+ZYy7IvQc/+mMsJ8epjEjAkEAwSXP5UZuJaS5fdmRA1pepucY904EBxrHCOjNmWXoLyWBJD22DE0MOSE1GM/cX7UXM1+VSAZ8Ho4PyJg822SzSwJAENH5NvLVuin4iNPuJook6W2gES5/xzlzZ63aL5EQZin4h9YKlbp6CxTGmQxrrbK5MD2mcoPg7bwWUJDv4jvSPQJBAJqd2Vnx0pUB05eiRgrIGgND9mFqq6DAV9qS+ps0z/SF8mZ/nC8msoU9RxMQuppHDkaK2qbowg13rbzn2bfLWhcCQE5+Ji28W58yy90qwQqLw5z1lkDjHh8nkVQg99pNodxiLRVo4Zt2Do711AxQb0Udw+y51jHwXCylw2Wq44MMx0M=";
String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCSEPnYEgIBCgCe1n9n7M7WEMJgwcGaFcJgQ3Jv0s3cQIfH9zqtw+bYISJo93ygE6y3aDGSxE51Z6CFSvk9NeCPICAlaE5hzbMm96aeK+N1tjQHGi/mEweFkVbgn8nvUFTrQakVSvXti7cI79IXmuoqgQ+PsNxm7vM1j3I0UbfeQQIDAQAB";

2、把Java密钥对转换为PHP密钥对(pem格式)

  • Java私钥为PKCS8格式,PHP使用的私钥为PKCS1格式,先将Java私钥转换为PKCS1格式,公钥不用转换,转换工具可以使用支付宝提供的签名工具

  • 然后将转换PKCS1后的私钥和原公钥转换为pem格式

/**
 * 将字符串格式公私钥格式化为pem格式公私钥
 * @param $secret_key
 * @param $type
 * @return string
 */
public static function format_secret_key($secret_key, $type){
    // 64个英文字符后接换行符"\n",最后再接换行符"\n"
    $key = (wordwrap($secret_key, 64, "\n", true))."\n";
    // 添加pem格式头和尾
    if ($type == 'pub') {
        $pem_key = "-----BEGIN PUBLIC KEY-----\n" . $key . "-----END PUBLIC KEY-----\n";
    }else if ($type == 'pri') {
        $pem_key = "-----BEGIN RSA PRIVATE KEY-----\n" . $key . "-----END RSA PRIVATE KEY-----\n";
    }else{
        echo('公私钥类型非法');
        exit();
    }
    return $pem_key;
}
  • 这样就得到了PHP能够使用的密钥对了

PHP生成密钥对

// 生成密钥对
$res = openssl_pkey_new();
openssl_pkey_export($res,$pri);
$d= openssl_pkey_get_details($res);
$pub = $d['key'];
var_dump($pri,$pub);

PHP签名、验签

// 私钥
$pri =<<

// 公钥
$pub = <<


// 生成base64签名
$openssl_pri = openssl_pkey_get_private($pri);
if (openssl_sign('hello', $sign, $openssl_pri)) {
    var_dump(base64_encode($sign));
}

// 验签
$sign = base64_decode(base64_encode($sign));
$openssl_pub = openssl_pkey_get_public($pub);
if (openssl_verify('hello', $sign, $openssl_pub) === 1)
    echo 'pass';
else
    echo 'not pass';

你可能感兴趣的:(PHP)