Skip to content

Instantly share code, notes, and snippets.

@sivsivsree
Created November 9, 2021 07:40
Show Gist options
  • Save sivsivsree/410c0fd47c01f1079c569fc136428d54 to your computer and use it in GitHub Desktop.
Save sivsivsree/410c0fd47c01f1079c569fc136428d54 to your computer and use it in GitHub Desktop.
json data signing and verification in node.js
const crypto = require('crypto');
const buffer = require('buffer');
const algorithm = "SHA256"
// Create a private key
const { privateKey,publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
});
// JSON object
const person = {
name: "Siv S",
email:"sivsivsree@hotmail.com",
address: "Dubai"
}
// Convert Stringified json data to buffer
const data = Buffer.from( JSON.stringify(person) );
// Sign the data and returned signature in buffer
const sign = crypto.sign(algorithm, data , privateKey);
// Convert returned buffer to base64
const signature = sign.toString('base64');
// Printing the signature
console.log(`Signature:\n\n ${signature}`);
// Verifying signature using crypto.verify() function
const isVerified = crypto.verify(
algorithm,
data,
publicKey,
Buffer.from(signature,'base64')
);
// Printing the result
console.log(`Is signature verified: ${isVerified}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment