Skip to content
Related Articles

Related Articles

Node.js crypto.setEngine() Function

Improve Article
Save Article
  • Last Updated : 26 May, 2022
Improve Article
Save Article

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, cypher, decode, sign, and verify methods.

The crypto.setEngine() function load and configure the engine for some or all OpenSSL functions, selected by the flags.

Syntax:

crypto.setEngine(engine[, flags])

Parameters:

  • engine: This is either an id or a path to the shared library of the engine.
  • flags: The flags are a bit field taking one of or a mix of the flags. It is used to select the class of functions. The default value is ENGINE_METHOD_ALL.

Example 1: Create a node.js project alongside a file named index.js and write the following code.

Javascript




const crypto = require("crypto");
  
crypto.setEngine("dynamic");
const secret = 'geeksforgeeks';
const hash = crypto
    .createHmac('sha256', secret)
    .update('I am a geek')
    .digest('hex');
console.log(hash);


Steps to run the application: You can run the code by typing the following line of code:

node index.js

Output:

 

Example 2: Create a node.js project alongside a file named index.js and write the following code.

Javascript




const crypto = require("crypto");
  
crypto.setEngine("dynamic", crypto.constants.ENGINE_METHOD_DH);
const dh = crypto.createDiffieHellman(512);
dh.generateKeys()
const publicKey = dh.getPublicKey();
console.log(publicKey);


Steps to run the application: You can run the code by typing the following line of code:

node index.js

Note: This limits the engine usage to only Diffie Hellman.

Output:

 

Reference: https://nodejs.org/dist/latest-v12.x/docs/api/crypto.html#crypto_crypto_setengine_engine_flags


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!