Yousef Amar
Yousef Amar

Reputation: 661

How can I generate a key pair and use it to sign and verify text in Node.js?

How can I generate a private and public key, use the private key to sign a hash of arbitrary text, then elsewhere use the public key to verify the signature?

Upvotes: 1

Views: 2134

Answers (1)

Yousef Amar
Yousef Amar

Reputation: 661

Using URSA (Node.js wrappers for OpenSSL crypto):

var ursa = require('ursa');

// Generate RSA private key (public key included)
var keyPair = ursa.generatePrivateKey();

// Convert public key to string
var pub = keyPair.toPublicPem('base64');

// Create buffer from text
var data = new Buffer('Hello, world!');

// Create MD5 hash and sign with private key
var sig = keyPair.hashAndSign('md5', data);

// Elsewhere...

// Create public key object from PEM string
pub = ursa.createPublicKey(pub, 'base64');

// Verify signature - should return true
pub.hashAndVerify('md5', data, sig);

Upvotes: 1

Related Questions