dcodeIO / bcrypt.js

Optimized bcrypt in plain JavaScript with zero dependencies.
Other
3.51k stars 267 forks source link

genSalt not working on nodejs esm #150

Open randrei12 opened 11 months ago

randrei12 commented 11 months ago

When I try to use genSalt function on es modules I get the following error: Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative. It works on commonjs.

I took a look into the bcryptjs source code and I found this:

function random(len) {
    /* node */ if (typeof module !== 'undefined' && module && module['exports'])
        try {
            return require("crypto")['randomBytes'](len);
        } catch (e) {}
    /* WCA */ try {
        var a; (self['crypto']||self['msCrypto'])['getRandomValues'](a = new Uint32Array(len));
        return Array.prototype.slice.call(a);
    } catch (e) {}
    /* fallback */ if (!randomFallback)
        throw Error("Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative");
    return randomFallback(len);
}

I believe the problem is that module['exports'] parameter, which, of course, doesn't exists in esm nodejs. I think a better verification method is to check if process object exists. Please take a look on this issue, thanks!