Open In App

NodeJS sign.sign(privateKey[, outputEncoding])

Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • privateKey: The private key. It can be passed as KeyObject, if not then we need to pass an object with the following parameters:
    • dataEncoding: The data encoding to be used. It can be either ‘der’ or ‘ieee-p1363’.
    • padding: The optional padding value for RSA.
    • saltLength: The salt length.
  • outputEncoding: The encoding of the return value.

Returns: The signature in form of Buffer or String.

Installing the crypto module:

npm install crypto

Project Structure:

 

package.json:

Javascript




{
  "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

Javascript




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

Javascript




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



Last Updated : 19 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads