使用nodejs验证RSA签名(使用phpseclib签名)

时间:2018-03-18 01:52:41

标签: php node.js rsa digital-signature phpseclib

我正在尝试将支付网关集成到我的nodejs应用。付款完成后,网关会将用户重定向到我的网站并显示付款结果。结果是RSA签名,我需要使用支付网关提供的公钥进行验证。

以下是支付网关提供签名验证的示例PHP代码。

<?php
include 'Crypt/RSA.php';
$rsa = new Crypt_RSA();
$payment = base64_decode($_POST ["payment"]);
$signature = base64_decode($_POST ["signature"]);
$publickey = "-----BEGIN PUBLIC KEY----- SOMEKEYSOMEKEYSOMEKEYSOMEKEYSOMEKEYSOMEKEYSOMEKEY -----END PUBLIC KEY-----";
$rsa->loadKey($publickey);
$signature_status = $rsa->verify($payment, $signature) ? TRUE : FALSE;
echo $signature_status; 
?>

PHP代码使用以下加密库进行签名验证。

https://github.com/phpseclib/phpseclib

我尝试了示例php代码,但它确实有效。

我试图通过以下方式在node-rsa库的帮助下验证签名。

const NodeRSA = require('node-rsa');
const decryptionKey = new NodeRSA(PUBLIC_KEY);
decryptionKey.setOptions({signingScheme: 'pss-sha1'});

module.exports.handlePaymentCallback = function (req, res, next) {
    const signature = Buffer.from(req.body.signature, 'base64').toString();
    const payment = Buffer.from(req.body.payment, 'base64').toString();
    let result = decryptionKey.verify(payment, signature);
}

但是签名验证失败了。我尝试将signingScheme更改为各种可能的方案(pss-sha256,pkcs1-sha256,pkcs1-sha1等),但它不起作用。

我也试过使用nodejs加密库,但仍然失败了。

const constants = process.binding('constants').crypto;
const crypt = require('crypto');

module.exports.handlePaymentCallback = function (req, res, next) {
    const signature = Buffer.from(req.body.signature, 'base64').toString();
    const payment = Buffer.from(req.body.payment, 'base64').toString();
    const verifier = crypt.createVerify('RSA-SHA1');
    verifier.update(new Buffer('' + payment, 'utf8'));
    const options = {key: PUBLIC_KEY};
    let result = verifier.verify(options, signature);
}

有谁知道如何完成这项工作?

1 个答案:

答案 0 :(得分:1)

我发现了问题。我不必要地拨打了toString()签名和付款缓冲区。删除toString()后,就可以了。

const NodeRSA = require('node-rsa');
const decryptionKey = new NodeRSA(PUBLIC_KEY);
decryptionKey.setOptions({signingScheme: 'pss-sha1'});

module.exports.handlePaymentCallback = function (req, res, next) {
    const signature = Buffer.from(req.body.signature, 'base64');
    const payment = Buffer.from(req.body.payment, 'base64');
    let result = decryptionKey.verify(payment, signature);
}