I am porting several packages created for NodeJS to React Native, using ReactNativify to rewrite Node dependent API objects to their monitored equivalents.
One of them is crypto . In transformer.js (or .babelrc ) I have:
// The following plugin will rewrite imports. Reimplementations of node // libraries such as `assert`, `buffer`, etc. will be picked up // automatically by the React Native packager. All other built-in node // libraries get rewritten to their browserify counterpart. [require('babel-plugin-rewrite-require'), { aliases: { crypto: 'crypto-browserify', // ... }, throwForNonStringLiteral: true, }],
ReactNativify global.js has this code (which I excluded because it is not intended for production):
// Don't do this in production. You're going to want to patch in // https://github.com/mvayngrib/react-native-randombytes or similar. global.crypto = { getRandomValues(byteArray) { for (let i = 0; i < byteArray.length; i++) { byteArray[i] = Math.floor(256 * Math.random()); } }, };
.
My first question is : how getRandomValues fixed correctly for production?
There is a second option that uses react-native-crypto ( crypto-browserify clone)
Ideally, I should just do this in transformer.js :
aliases: { crypto: 'react-native-crypto', // instead of 'crypto-browserify' // ... },
But react-native-crypto uses rn-nodeify instead of ReactNativify, which generates shim.js to import into index.android.js / index.ios.js with code like this:
if (require('./package.json').dependencies['react-native-crypto']) { const algos = require('browserify-sign/algos') if (!algos.sha256) { algos.sha256 = { "sign": "ecdsa", "hash": "sha256", "id": new Buffer("") } } if (typeof window === 'object') { const wCrypto = window.crypto = window.crypto || {} wCrypto.getRandomValues = wCrypto.getRandomValues || getRandomValues } const crypto = require('crypto') const randomBytes = crypto.randomBytes crypto.randomBytes = function (size, cb) { if (cb) return randomBytes.apply(crypto, arguments) const arr = new Buffer(size) getRandomValues(arr) return arr } crypto.getRandomValues = crypto.getRandomValues || getRandomValues function getRandomValues (arr) {
I don't know if all this padding code is needed when using ReactNativify and cannot find good sources, so ...
My second question . How to use react-native-crypto in the correct ReactNativify path?
I created github issues in ReactNativify and response-native-crypto repo:
Versions:
node 7.10.1 /usr/local/bin/node npm 4.2.0 /usr/local/bin/npm yarn 0.24.6 /usr/bin/yarn react-native-cli 2.0.1 app rn version 0.45.1 ignite 2.0.0 /usr/local/bin/ignite