使用nodejs crypto签名/验证始终为false

时间:2018-12-31 08:36:19

标签: node.js

我需要签名并验证node.js中的消息。我遵循了crypto软件包document,但是我总是在verify方法上得到false,这表明签名不正确。

我正在使用的RSA public keyprivate key可以很好地用于使用相同的crypto包对消息进行加密/解密。

代码如下:

var crypto = require("crypto");
var eol = require('os').EOL;

签名和验证方法:

function RSASign(privateKey, data) {
    const sign = crypto.createSign('RSA-SHA256');
    sign.update(data);
    var sig = sign.sign(privateKey, 'hex')
    console.log(sig);
    return sig;
}

function RSAVerify(publicKey, signature, data) {
    const verify = crypto.createVerify('RSA-SHA256');
    verify.update(data);
    console.log(verify.verify(publicKey, signature));
}

我正在使用

调用方法
var dataToSign = "some data";
var sig = RSASign(privateKey, dataToSign);
RSAVerify(publicKey, sig, dataToSign);

公钥:

var pubStr = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCbbBSVpWzSmCGVeezhuVFgUEYowUxgX/SnFdymGRCHGc77d5I0xkMAnIOWbI2MmP8j/7sdfPuUF0V5zw+Hd/7iZ6vs2k4JRKdprrB/zSC4GGqCDpDkbRYydcw3kwDgKkHhDp6NwIKvvl87WsnFozi487tGPQ8NO15hngwsV7DrawIDAQAB';
var publickKey = '-----BEGIN PUBLIC KEY-----' + eol + pubStr + eol + '-----END PUBLIC KEY-----';

私钥:

var p = 'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJtsFJWlbNKYIZV57OG5UWBQRijBTGBf9KcV3KYZEIcZzvt3kjTGQwCcg5ZsjYyY/yP/ux18+5QXRXnPD4d3/uJnq+zaTglEp2musH/NILgYaoIOkORtFjJ1zDeTAOAqQeEOno3Agq++XztaycWjOLjzu0Y9Dw07XmGeDCxXsOtrAgMBAAECgYAV13iFFzxV1B9UHFBX4G05Nc7GR3PuT03YdVAO35LdCZl26XTYicw8t8IeT58M1St16ahoGnpYc3TGC31JMmnVOr58At0jbd4JQgvUaE+2jVvgp0Lc6n/jN+7NYBGlEy44ZpIRbB1Biu7khCZ0D+8PZsDMi6WJK4jgI5Gf/aXvkQJBAOe6809U/1wEVDJFHZ6A++WI/8iebXSbw9hDa4a9qoXv8bsMjYkDiblD3UPRlTEdFsAOA/YuGdah+fKE7jKdKkcCQQCrszD8Z1MYWYE4dMQTRPxEKHGQZd5HHkTQu9l6FV7Bv2ga9wLhT4QTb/5U7WYGgbfxhFzklxoqsmhTJNuLlyO9AkBrA1nDZBQ9MT6UrHheL2Ckgpzkz8zqUdiicZghdEtgaQtv/v8JrBmY9e8jl5DXSoCsFozbzjReexTLW3oI462XAkEAnTQ/kZl4tz6b1XjzXUE4R59P+wmJ7kuEbijQAbs3OuVpB+dJN8l5/+H2VwPU+fgi1np+Ir1GM/mNEzMX4ELNcQJBAIk1s3Y7ep2gK0p4js4f9HU0u2vH25+6bu+y6JFfvIBd8OR1bCFEe3FIui1H/ohh0Eoo3ZgJZ/5JjwfsqJzOoBs=';
var privateKey = '-----BEGIN PRIVATE KEY-----' + eol + p + eol + '-----END PRIVATE KEY-----'

我想念什么?

1 个答案:

答案 0 :(得分:1)

在验证verify.verify(publicKey, signature,'hex')时,您必须包括在编码过程中使用的signatureEncoding

verify signature

 function RSAVerify(publicKey, signature, data) {
        const verify = crypto.createVerify('RSA-SHA256');
        verify.update(data);
        console.log(verify.verify(publicKey, signature,'hex'));
    }