Skip to content

n.randomBytes is not a function #602

Open

Description

@bradleyhodges

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

Activity

  1. KunalOjha commented on Sep 30, 2019

    @KunalOjha

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

  2. davidlehn commented on Oct 4, 2019

    @davidlehn
    Member

    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.

  3. mattnotmitt commented on Apr 7, 2020

    @mattnotmitt

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

  4. ben-yocum commented on May 22, 2020

    @ben-yocum

    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.

  5. added a commit that references this issue on May 26, 2020
  6. ben-yocum commented on May 26, 2020

    @ben-yocum

    PR submitted #782

  7. Thulof commented on Mar 1, 2025

    @Thulof

    I have created a new PR #1110 to fix it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions