4

我正在将一些为 NodeJS 创建的包移植到 React Native,使用ReactNativify将 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,
}],

在 ReactNativifyglobal.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正确修补生产?


还有第二个选项,那就是使用react-native-crypto(的克隆crypto-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 时是否需要所有这些 shim 代码,并且找不到好的来源,所以......

我的第二个问题:如何以react-native-crypto“正确的 ReactNativify 方式”使用?


我在 ReactNativify 和 react-native-crypto repo 中创建了 github 问题:

版本:

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
4

0 回答 0