简体   繁体   中英

Using crypto to sign and verify strings

I'm playing around with Node's Crypto's generateKeyPairSync , Sign and Verify but I can't get this ridiculously simple code to work: verify.verify always output false, eventhough it should output true. What am I missing?

const crypto = require('crypto');

const txt = 'Some text to sign';

// generates asymmetric key pair
const keys = crypto.generateKeyPairSync('rsa', {
    modulusLength: 4096,
    publicKeyEncoding: {
        type: 'pkcs1',
        format: 'pem'
    },
    privateKeyEncoding: {
        type: 'pkcs1',
        format: 'pem',
    }
});

// generates a signature object
const sign = crypto.createSign('sha256');
sign.update(txt);

// generates a verify object
const verify = crypto.createVerify('sha256');
verify.update(txt);

// should logs true, but logs false
console.log(
    verify.verify(
        keys.publicKey,
        sign.sign(keys.privateKey, 'base64')
    )
);

You can precise signature_format: "latin1" | "hex" | "base64" signature_format: "latin1" | "hex" | "base64" signature_format: "latin1" | "hex" | "base64" as the third argument of verify.verify . This returns true , as expected:

verify.verify(
    keys.publicKey,
    sign.sign(keys.privateKey, 'base64'),
    'base64'
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM