Generating JWT in react native

2019-07-17 16:40发布

问题:

I am trying to generate JWT in React Native. The react-native-jwt module is based on Node's jwt-simple. It uses react-native-crypto, which is a partial clone of crypto-browserify with certain workarounds to get crypto working outside of the web browser.

The problem is that randombytes (subdependency of react-native-jwt) can't find crypto.

browser.js:

'use strict'

function oldBrowser () {
  throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11')
}

var crypto = global.crypto || global.msCrypto // GETS SET TO 'UNDEFINED'

if (crypto && crypto.getRandomValues) {
  module.exports = randomBytes
} else {
  module.exports = oldBrowser
}

function randomBytes (size, cb) {
  // phantomjs needs to throw
  if (size > 65536) throw new Error('requested too many random bytes')
  // in case browserify  isn't using the Uint8Array version
  var rawBytes = new global.Uint8Array(size)

  // This will not work in older browsers.
  // See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
  if (size > 0) {  // getRandomValues fails on IE if size == 0
    crypto.getRandomValues(rawBytes)
  }
  // phantomjs doesn't like a buffer being passed here
  var bytes = new Buffer(rawBytes.buffer)

  if (typeof cb === 'function') {
    return process.nextTick(function () {
      cb(null, bytes)
    })
  }

  return bytes
}

Note: It appears that crypto is only available on Android and I need it on iOS.