Created
November 9, 2021 07:40
-
-
Save sivsivsree/410c0fd47c01f1079c569fc136428d54 to your computer and use it in GitHub Desktop.
json data signing and verification in node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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:"[email protected]", | |
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