如何为React Native补丁/ shim crypto.getRandomValues

时间:2017-07-25 11:27:49

标签: node.js react-native browserify browserify-shim libsodium

我正在使用ReactNativify将为NodeJS创建的一些包移植到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如何正确修补生产?

还有第二种选择,就是使用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和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

0 个答案:

没有答案