Home > Software engineering >  how to expose node Crypto cipher.update() function in electron
how to expose node Crypto cipher.update() function in electron

Time:11-01

Iam creating an electron app and i want to use the node crypto library in the electron app. I have used electron contextBridge using preload.js to expose node crypto but how do i expose the cipher.update() function.

// preload.js
const { contextBridge } = require('electron');
const nodeCrypto = require('crypto');

const { contextBridge } = require('electron');
contextBridge.exposeInMainWorld('nodeCrypto', {
    randomBytes: (size) => nodeCrypto.randomBytes(size),
    pbkdf2Sync: (...args) => nodeCrypto.scryptSync(...args),
    createCipheriv: (...args) => nodeCrypto.createCipheriv(...args),
    createDecipheriv: (...args) => nodeCrypto.createDecipheriv(...args)
});

Want to use cipher.update() like this

function encrypt() {
    const salt = nodeCrypto.randomBytes(16);
    const key = nodeCrypto.scryptSync('password', 'salt', 64, { N: 1024 });
    const cipher = nodeCrypto.createCipheriv("aes-256-gcm", key, salt);
    const encryptedData = Buffer.concat([cipher.update(data), cipher.final()]);
}

CodePudding user response:

You can completely define your methods in your preload.js and expose them to the renderer processes to remove the hassle of exposing every needed method.

Thus, I propose to use the following code for your preload.js:

const { contextBridge } = require('electron');
const nodeCrypto = require('crypto');

const encrypt = (data) => {
    const salt = nodeCrypto.randomBytes(16);
    const key = nodeCrypto.scryptSync('password', 'salt', 64, { N: 1024 });
    const cipher = nodeCrypto.createCipheriv("aes-256-gcm", key, salt);
    const encryptedData = Buffer.concat([cipher.update(data), cipher.final()]);
};

const { contextBridge } = require('electron');
contextBridge.exposeInMainWorld('customCrypto', {encrypt});

Please note that I renamed your namespace (nodeCryptocustomCrypto) to remove any possible confusion and added data as a paremeter to your encrypt function since it was missing from your original code and it would thus not have worked.

In your renderer process, you can call this function as follows:

window.customCrypto.encrypt (/* data */);

In case you want to expose more functions (say, decrypt and validate for example) in the future, the preload.js context bridge definition would look like this:

contextBridge.exposeInMainWorld('customCrypto', {encrypt, decrypt, validate});
  • Related