Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Native crypto module could not be used to get secure random number. #256

Closed
kangyunu opened this issue Feb 11, 2020 · 45 comments
Closed

Native crypto module could not be used to get secure random number. #256

kangyunu opened this issue Feb 11, 2020 · 45 comments

Comments

@kangyunu
Copy link

crypto-js npm runkit error.

var CryptoJS = require("crypto-js");

// Encrypt
var ciphertext = CryptoJS.AES.encrypt('my message', 'secret key 123');

// Decrypt
var bytes  = CryptoJS.AES.decrypt(ciphertext.toString(), 'secret key 123');
var plaintext = bytes.toString(CryptoJS.enc.Utf8);

run.

Error: Native crypto module could not be used to get secure random number.

@liamross
Copy link

I'm having the same issue, thrown during encryption using any of the cypher algorithms

@liamross
Copy link

@rkdqudtjs1 Hmm, the fix is to not use v3.2.0 but instead fix the version to v3.1.9-1

@kangyunu
Copy link
Author

@rkdqudtjs1 Hmm, the fix is to not use v3.2.0 but instead fix the version to v3.1.9-1

Thanks @liamross

@debugrammer
Copy link

debugrammer commented Feb 11, 2020

I got same issue after upgraded to [email protected].
Both web browser (Chrome 80.0.3987.87) and Node.js interpreter (v12.15.0) throwing same error.

Seems like the error was thrown from below code lines (which were added on v3.2.0) in core.js.

/*
 * Cryptographically secure pseudorandom number generator
 *
 * As Math.random() is cryptographically not safe to use
 */
var secureRandom = function () {
    // Native crypto module on NodeJS environment
    try {
        // Crypto from global object
        var crypto = global.crypto;

        // Create a random float number between 0 and 1
        return Number('0.' + crypto.randomBytes(3).readUIntBE(0, 3));
    } catch (err) {}

    // Native crypto module in Browser environment
    try {
        // Support experimental crypto module in IE 11
        var crypto = window.crypto || window.msCrypto;

        // Create a random float number between 0 and 1
        return Number('0.' + window.crypto.getRandomValues(new Uint32Array(1))[0]);
    } catch (err) {}

    throw new Error('Native crypto module could not be used to get secure random number.');
};

@wartab
Copy link

wartab commented Feb 11, 2020

That code does not generate a uniformly distributed floating point number anyway, therefore is probably even more insecure than Math.random().

https://nodejs.org/api/buffer.html#buffer_buf_readfloatle_offset

Regardless of this, what this does is non-sense, as the only use of that function is to generate random bytes with the random() method of WordArray. Why not just use the crypto libraries of the browser and node to actually generate random bytes rather than generating bytes with hazardous multiplication of a restricted inaccurate floating point number?

@harendra-iitg
Copy link

Error: Native crypto module could not be used to get secure random number.

"crypto-js": "^3.1.9-1"

How to fix this ? Critical Issue

@evanvosberg
Copy link
Member

The new 3.2.0 version has a critical bug / vulnerability.
Work on a fix is in progress.

@kyle-ssg
Copy link

Just in case anyone stumbles onto this, it looks like this is breaking any react native project using simple-crypto-js, particularly in AppCenter which I assume is due to it being a Linux distribution.

@liamross
Copy link

@harendra-iitg

Error: Native crypto module could not be used to get secure random number.

"crypto-js": "^3.1.9-1"

How to fix this ? Critical Issue

You may have to fix the version at 3.1.9-1, as I'm pretty sure specifying ^3.1.9-1 will still install 3.2.0.

- "crypto-js": "^3.1.9-1"
+ "crypto-js": "3.1.9-1"

@evanvosberg
Copy link
Member

This is the pull request #257 working on a fix.

Reviews are welcome, don't want to mess it up again.

@evanvosberg
Copy link
Member

There is a new version 3.2.1.

Please keep in mind, that 3.2.x now uses the JavaScripts native crypto module to generate random numbers. Due to this move CryptoJS does not run in environments without a native crypto module. The native crypto module is available in modern browsers (even IE 11) and in NodeJS.

@alexyangjie
Copy link

Does that mean we can't use 3.2.x in React Native apps? It throws error crypto could not be found within the project.

@evanvosberg
Copy link
Member

Yes, than you have to stay with 3.1.x.

That's why it's added in the release notes.

If you find another way to provide cryptographically secure random numbers without crypto module, you're welcome to share the solution.

@evanvosberg
Copy link
Member

evanvosberg commented Feb 12, 2020

For all using CryptoJS in React Native please help to review this pull request #259.

@gHashTag
Copy link

I do not use crypto, but I also use AWS Amplify with react-native. I get this error. How to fix?

@gHashTag
Copy link

gHashTag commented Feb 12, 2020

That decides me!

 "resolutions": {
    "crypto-js": "3.1.9-1"
  }

aws-amplify/amplify-js#4886 (comment)

@wartab
Copy link

wartab commented Feb 12, 2020

Why did you not release a major version for such a breaking change? Please release 3.2.2 with whatever was in 3.1 and make a 4.0.0 for the new stuff. That's what semver is there for.

@evanvosberg
Copy link
Member

As the 3.2.0 is out and broaken and it can't be removed anymore, just marked as deprecated, I decided to stay with 3.2.x.

@wartab
Copy link

wartab commented Feb 12, 2020

Hence why you should release 3.2.2 with whatever works in 3.1 and release a major version so this does not impact libraries that use semver correctly.

@evanvosberg
Copy link
Member

Provided a version 3.3.0 which is a rollback, just same as 3.1.9-1.

There is a new 4.0.0 version, due to the lack of native crypto module in React Native, this version does not run in React Native yet.

@tylerlindell
Copy link

tylerlindell commented Apr 11, 2022

This response is for anyone landing here and getting an error from aws-amplify or amazon-cognito-identity-js library.

This answer is not related to crypto-js

it looks like this issue may be coming up for many people due to the context in which they are executing the amazon-cognito-identity-js library. There is a piece of code in the node_modules/amazon-cognito-identity-js/lib/utils/cryptoSecureRandomInt.js file that is looking to assign value to the crypto variable. The value is intended to be fetched from the window object.

// node_modules/amazon-cognito-identity-js/lib/utils/cryptoSecureRandomInt.js

var crypto; // Native crypto from window (Browser)

if (typeof window !== 'undefined' && window.crypto) {
  crypto = window.crypto;
} // Native (experimental IE 11) crypto from window (Browser)


if (!crypto && typeof window !== 'undefined' && window.msCrypto) {
  crypto = window.msCrypto;
} // Native crypto from global (NodeJS)


if (!crypto && typeof global !== 'undefined' && global.crypto) {
  crypto = global.crypto;
} // Native crypto import via require (NodeJS)


if (!crypto && typeof require === 'function') {
  try {
    crypto = require('crypto');
  } catch (err) {}
}

If for some reason crypto does not get assigned or crypto object does not have an expected function available, an error is thrown in the cryptoSecureRandomInt function

// node_modules/amazon-cognito-identity-js/lib/utils/cryptoSecureRandomInt.js

function cryptoSecureRandomInt() {
  if (crypto) {
    // Use getRandomValues method (Browser)
    if (typeof crypto.getRandomValues === 'function') {
      try {
        return crypto.getRandomValues(new Uint32Array(1))[0];
      } catch (err) {}
    } // Use randomBytes method (NodeJS)


    if (typeof crypto.randomBytes === 'function') {
      try {
        return crypto.randomBytes(4).readInt32LE();
      } catch (err) {}
    }
  }

  throw new Error('Native crypto module could not be used to get secure random number.');
}

In my case, I'm getting this error when testing a React App using Jest while my jest config file is setup to use the testEnvironment of jsdom I still get this error with crypto.

A way I found to correct this issue while testing with jest is to use the following

// <rootDir>/src/__mocks__/cryptoSetup.js

global.crypto = { 
    getRandomValues: (arr) => require('crypto').randomBytes(arr.length) 
};

and inform my jest config to use this file as a setup file like this

// jest.config.js

setupFiles: [
        ...,
        "<rootDir>/src/__mocks__/cryptoSetup.js"
    ]

I came across this part of the solution here

@nasiriyima
Copy link

nasiriyima commented Apr 22, 2022

Downloaded this library and landed here on 22/04/2022. But unfortunately, it seems this error still persists till date and downgrading to 3.1.9-1 still seems to be the valid solution to this problem........

@ranfysvalle02
Copy link

05/01/2022 - Still a problem.... The fix is as stated above, "3.1.9-1"

@AlenToma
Copy link

AlenToma commented Jul 1, 2022

having this issue with react-native:0.69.1 and using "crypto-js": "^4.1.1"

@kukadiyaAni
Copy link

@AlenToma right react-native:0.69.1 and using "crypto-js": "^4.1.1"

did you get any solution?

@weizixuanDavid
Copy link

solution
now my envirment is react-native:0.69.4 and using "crypto-js":"^4.1.1", the problem still occurs....

@gustavosantaella
Copy link

I have the same error. I'm using "react-native": "0.68.2", and "crypto-js": "^4.1.1",

Does anyone have a solution?

@josephbima
Copy link

@rkdqudtjs1 Hmm, the fix is to not use v3.2.0 but instead fix the version to v3.1.9-1

I'm here to say that as of 9/17/2021, this is the solution that [still] works. I had the latest version (4.1.1) and was receiving the error within the Expo framework. I switched to 3.1.9-1 as a hail mary, and it worked. Thanks!

This still works today(2021/09/27)

This still works today(2021/10/27)

This still works today (2022/10/12)

@mizutani256
Copy link

If this issue occurs in React-native 0.64 use #259 (comment)

This also worked as of 2022/10/17

@sajithads
Copy link

@rkdqudtjs1 Hmm, the fix is to not use v3.2.0 but instead fix the version to v3.1.9-1

I'm here to say that as of 9/17/2021, this is the solution that [still] works. I had the latest version (4.1.1) and was receiving the error within the Expo framework. I switched to 3.1.9-1 as a hail mary, and it worked. Thanks!

This still works today(2021/09/27)

This still works today(2021/10/27)

This still works today (2022/10/12)

Also worked as of 2022/12/6 when using it alongside Atlas MongoDB triggers

@inapeace0
Copy link

Hi, everyone. I got the same issue with [email protected] and [email protected].
Perfect solution for it? Thanks.

@SandraLum
Copy link

Hi, everyone. I got the same issue with [email protected] and [email protected]. Perfect solution for it? Thanks.

I am on [email protected], [email protected] and [email protected]
The following works for me:

  1. yarn add react-native-get-random-values , i am on [email protected]
  2. In your App.js add import 'react-native-get-random-values' at the top

@Waddas
Copy link

Waddas commented May 8, 2023

Getting the same issue with react-native 0.71.7 and crypto-js 4.1.1. The fix for me is to downgrade crypto-js to 3.1.9-1 as mentioned above. Not sure why the issue is closed?

@kpose
Copy link

kpose commented May 19, 2023

@Waddas This worked for me. RN 0.69, crypto-js: 4.1.1

@choijiho0021
Copy link

안녕하세요 여러분. [email protected][email protected]에서 동일한 문제가 발생했습니다. 완벽한 솔루션? 감사해요.

나는 에 있으며 [email protected]다음 은 나를 위해 작동합니다.[email protected]``[email protected]

  1. yarn add react-native-get-random-values, 나는 켜져있다[email protected]
  2. App.js에서 import 'react-native-get-random-values'상단에 추가

@SandraLum
RN 0.68.5, crypto-js: 4.1.1
it's working perfectly!! Thank you bro

frostehhh added a commit to frostehhh/google-keep-clone that referenced this issue Sep 24, 2023
Add logic to check if global exists. Move existing condition blocks into
this block. Note that these global checks are for non-browser
environments. For browser environments, add similar polyfill
via the window global variable.

Reference:
- brix/crypto-js#256 (comment)
frostehhh added a commit to frostehhh/google-keep-clone that referenced this issue Sep 24, 2023
Add logic to check if global exists. Move existing condition blocks into
this block. Note that these global checks are for non-browser
environments. For browser environments, add similar polyfill
via the window global variable.

Reference:
- brix/crypto-js#256 (comment)
frostehhh added a commit to frostehhh/google-keep-clone that referenced this issue Sep 24, 2023
Add logic to check if global exists. Move existing condition blocks into
this block. Note that these global checks are for non-browser
environments. For browser environments, add similar polyfill
via the window global variable.

Reference:
- brix/crypto-js#256 (comment)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests