最近做支付验签。java签名用的是md5withrsa。用nodejs验签。
function formatPKCKey(key, isPrivate, isFirst) {
var len = key.length;
var result = isPrivate ? "-----BEGIN PRIVATE KEY-----\r\n" : "-----BEGIN PUBLIC KEY-----\r\n";
var index = 0;
var count = 0;
while (index < len) {
var ch = key[index];
if (ch === '\r' || ch === '\n' || ch === '\r\n') {
++index;
continue;
}
result += ch;
if (++count === 64) {
result += '\r\n';
count = 0;
}
index++;
}
//如果是1.0
if (isFirst) {
result += "\r\n-----END RSA PRIVATE KEY-----";
} else {
result += isPrivate ? "\r\n-----END PRIVATE KEY-----" : "\r\n-----END PUBLIC KEY-----";
}
return result;
}
var srcstr = "POSID=02098***&BRANCHID=43000***&ORDERID=hnlebokeji888881530762423198&PAYMENT=0.01&CURCODE=01&REMARK1=&REMARK2=&ACC_TYPE=12&SUCCESS=Y&TYPE=1&REFERER=&CLIENTIP=11.168.64.165&ACCDATE=20180705";
var sig = "2369f285b188070ce5dcaff0fef5f5bb837770d7dcaa3b66953ccd663917b510e4d4a73d120dece4ab84c770c88b3de8677322afd036f1a4d6bde7407e5b7e14a22f8416477ce7e61b82a3e11c33198b71a8ad64bc606a3a93ee4c1321d4be2ae10e8d0a35b7914ea1a6ea55197aaa8e7645b0c5632ca549580b2d056722b975";
var pubkey = "30819d300d06092a864886f70d010101050003818b0030818702818100ddce12f24ea8d98f79ef515d71790bafc749af73b0eb1fa8c478b419c7720370d4d5412db64b7546c64208a1e98aa8bd03a8c87be8711063f9b53a14b83e0771ad7a031637343c251c00e1c24ac7ea6769b3c049e87244e2e6ff1da65e31b5f19018702fa791aab0713f5daa3cfe9cb65d362ef00d37e24bb8677a1********";
pubkey = Buffer.from(pubkey, 'hex').toString("base64");//先将16进制字符串转成base64位
pubkey = formatPKCKey(pubkey, false, false);//转成需要的pem格式。
var crypto = require('crypto');
var verify = crypto.createVerify('md5WithRSAEncryption');
verify.update(srcstr);//srcstr是原串串
var verifyResult = false;
try {
verifyResult = verify.verify(pubkey, Buffer.from(sin, 'hex'));//pubkey是公钥。需转成pem格式。sin参数是签名串。我们返回的签名串是一个16进制的字符串。因此。我把它转成buffer格式。
} catch (e) {
verifyResult=false;
};
return verifyResult;