forge icon indicating copy to clipboard operation
forge copied to clipboard

n.randomBytes is not a function

Open bradleyhodges opened this issue 7 years ago • 6 comments

When trying to execute forge.pki.encryptRsaPrivateKey(keypair.privateKey, password); in an Electron app, the exception n.randomBytes is not a function is thrown.

I've double checked, and this issue doesn't occur when executed in a Google Chrome tab. Here's the script I'm using:

var rsa = forge.pki.rsa; var password = "(this is retrieved elsewhere)";
rsa.generateKeyPair({bits: 2048, workers: 2}, function(err, keypair) {
    var publicKey = forge.pki.publicKeyToPem(keypair.publicKey);
    var privateKey = forge.pki.encryptRsaPrivateKey(keypair.privateKey, password);
});

By the looks of it, the exception is occurring when trying to execute the forge.pki.encryptRsaPrivateKey function in Electron.

Here's what the exception looks like in the DevTools: image

and this is where the exception appears to occur: image

bradleyhodges avatar Aug 03 '18 07:08 bradleyhodges

@bradleyhodges has there been any updates or workarounds to this bug?

KunalOjha avatar Sep 30 '19 22:09 KunalOjha

Might be the node vs browser code path logic. I'm not sure what happens in Electron. Try running with non-minimized code so it's easier to see what it's doing. Maybe that detection code can be fixed up.

davidlehn avatar Oct 04 '19 19:10 davidlehn

@davidlehn I'm currently having this issue, I've had a look in the minified JS and no require('crypto') call exists.

mattnotmitt avatar Apr 07 '20 19:04 mattnotmitt

Easy workaround:

if (process && !process.versions['node-webkit']) {
  process.versions['node-webkit'] = true;
}
const forge = require('node-forge');

A quick explanation of what's happening:

Forge is trying to use Node's crypto library, but is instead grabbing Chromium's crypto library. Normally Chromium's version would get overriden in a situation like this, but window.crypto is readonly, so it isn't happening.

I'm looking into making a PR to handle Electron the same way as Node-Webkit.

ben-yocum avatar May 22 '20 16:05 ben-yocum

PR submitted https://github.com/digitalbazaar/forge/pull/782

ben-yocum avatar May 26 '20 03:05 ben-yocum

I have created a new PR https://github.com/digitalbazaar/forge/pull/1110 to fix it.

Thulof avatar Mar 01 '25 10:03 Thulof