Open In App

NodeJS sign.sign(privateKey[, outputEncoding])

Node.js is a cross-platform, open-source back-end JavaScript runtime environment that uses the V8 engine to execute JavaScript code outside of a web browser. Node.js allows developers to utilize JavaScript to create command-line tools and server-side scripting, which involves running scripts on the server before sending the page to the user’s browser. Cryptographic functionality is provided via the crypto module, which includes wrappers for OpenSSL’s hash, HMAC, cipher, decode, sign, and verify methods.

The sign.sign() method is used to calculate the signature depending on the data passed. It uses either sign.update() or sign.write() to calculate.



Syntax:

sign.sign(privateKey[, outputEncoding])

Parameters:



Returns: The signature in form of Buffer or String.

Installing the crypto module:

npm install crypto

Project Structure:

 

package.json:




{
  "name": "crypto",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
    
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Example 1:

Filename: index.js




import { generateKeyPairSync, createSign } from 'crypto'
  
const { privateKey, publicKey } = generateKeyPairSync("rsa", {
    modulusLength: 2048,
});
  
let sign = createSign('SHA256');
  
let data = sign.sign(privateKey);
console.log(data.toString('hex'));

Output:

 

Example 2:

FileName: index.js




import { generateKeyPairSync, createSign } from 'crypto'
  
const { privateKey, publicKey } = generateKeyPairSync("ec", {
    namedCurve: "sect239k1",
});
let sign = createSign('SHA256');
  
let data = sign.sign(privateKey, 'base64');
console.log(data);

Output:

 

Reference: https://nodejs.org/api/crypto.html#signsignprivatekey-outputencoding


Article Tags :