如何为React Native修补/填充crypto.getRandomValues

我使用ReactNativify将一些为NodeJS创build的包移植到React Native,以将Node API对象依赖项重写为他们的browserify等价物。

其中之一是crypto 。 在transformer.js (或.babelrc )中我有:

 // 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有这样的代码(我排除了,因为它不适用于生产):

 // 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()); } }, }; 

我的第一个问题getRandomValues如何正确地打补丁生产?


还有第二种select,那就是使用react-native-cryptocrypto-browserify的克隆)

理想情况下,我应该能够在transformer.js做到这一点:

  aliases: { crypto: 'react-native-crypto', // instead of 'crypto-browserify' // ... }, 

但是react-native-crypto使用rn-nodeify而不是ReactNativify,它会生成一个shim.js来导入到index.android.js / index.ios.js ,代码如下:

 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) { // console.warn('WARNING: generating insecure psuedorandom number') for (var i = 0; i < arr.length; i++) { arr[i] = Math.random() * 256 | 0 } return arr } } 

我不知道使用ReactNativify时是否需要所有这些填充代码,并且找不到好的源代码,所以…

我的第二个问题 :如何在正确的ReactNativify方法中使用react-native-crypto


我已经在ReactNativify中创build了github问题,并反应了native-crypto的回购:

  • 如何在生产中使用getRandomValues?
  • 使用ReactNativify而不是rn-nodeify?

版本:

 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 

Interesting Posts