Giter Site home page Giter Site logo

react-native-crypto's Introduction

react-native-crypto

Note: this module is a clone of crypto-browserify, with randombytes replaced.

A port of node's crypto module to React Native.

DEPRECATED

you should probably use a combination of:

  • react-native-get-random-values to shim getRandomValues
  • crypto-browserify

install

Because this module depends on some node core modules, and react-native doesn't currently have a resolve.alias a la webpack, you will need to use rn-nodeify for your shimming needs.

A suggested workflow:

  1. Install
npm i --save react-native-crypto
# install peer deps
npm i --save react-native-randombytes
react-native link react-native-randombytes # on RN >= 0.60, instead do: cd iOS && pod install
# install latest rn-nodeify
npm i --save-dev rn-nodeify
# install node core shims and recursively hack package.json files
# in ./node_modules to add/update the "browser"/"react-native" field with relevant mappings
./node_modules/.bin/rn-nodeify --hack --install
  1. rn-nodeify will create a shim.js in the project root directory
// index.ios.js or index.android.js
// make sure you use `import` and not require!  
import './shim.js'
import crypto from 'crypto'
// ...the rest of your code

example

see https://github.com/mvayngrib/rncryptoexample

the crypto in this box

What follows is unedited text from crypto-browserify

The goal of this module is to reimplement node's crypto module so that it can run in react-native supported environments.

Here is the subset that is currently implemented:

  • createHash (sha1, sha224, sha256, sha384, sha512, md5, rmd160)
  • createHmac (sha1, sha224, sha256, sha384, sha512, md5, rmd160)
  • pbkdf2
  • pbkdf2Sync
  • randomBytes
  • pseudoRandomBytes
  • createCipher (aes)
  • createDecipher (aes)
  • createDiffieHellman
  • createSign (rsa, ecdsa)
  • createVerify (rsa, ecdsa)
  • createECDH (secp256k1)
  • publicEncrypt/privateDecrypt (rsa)
  • randomFillSync
  • randomFill

todo

these features from node's crypto are still unimplemented.

  • createCredentials
  • scryptSync

these features would benefit from native implementations

  • pbkdf2
  • createSign
  • createVerify
  • createECDH
  • publicEncrypto/privateDecrypt (rsa)

contributions

If you are interested in writing a feature, please implement as a new module, which will be incorporated into crypto-browserify as a dependency.

All deps must be compatible with node's crypto (generate example inputs and outputs with node, and save base64 strings inside JSON, so that tests can run in the browser. see sha.js

Crypto is extra serious so please do not hesitate to review the code, and post comments if you do.

License

MIT

react-native-crypto's People

Contributors

awlayton avatar biggillystyle avatar calvinmetcalf avatar coderpuppy avatar danilowoz avatar dcousens avatar dominictarr avatar edef1c avatar facundoolano avatar forbeslindesay avatar jd20 avatar jprichardson avatar kyledrake avatar legastero avatar lsegal avatar mosch avatar mvayngrib avatar orangemug avatar pcowgill avatar perezd avatar plediii avatar qalqi avatar rajivshah3 avatar ralphtheninja avatar sokra avatar tonistiigi avatar xwartz avatar zaach avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-crypto's Issues

Consider using expo-random as the peer dep so that ejecting from an Expo app isn't required

Consider using expo-random as the peer dep rather than react-native-randombytes so that ejecting from an Expo app isn't required in order to use react-native-crypto.

This would involve a polyfill that matches the node core crypto.randomBytes API exactly but uses the expo-random methods internally rather than react-native-randombytes methods.

expo-random works in both "managed" and "bare" Expo apps as well as vanilla React Native apps (Source)

TypeError: Cannot read property 'random' of undefined

I am trying to use an XMPP server as signalling server for webRTC audio and video chat. So I am using 'stanza' library to communicate with XMPP server. In order to signal the server, I am using 'Jingle'. But after setting up the react-native environment for 'stanza', I am getting the following error in the console.

[Fri Aug 06 2021 09:47:13.865]  LOG      There was an error collecting entropy from the browser:
[Fri Aug 06 2021 09:47:13.866]  LOG      [TypeError: undefined is not an object (evaluating 'sjcl.random')]
[Fri Aug 06 2021 09:47:13.867]  LOG      Running "webrtcApp" with {"rootTag":1}

React-native version is 0.62.2
I have gone through the issues at #10. But that doesn't work for me.

Can somebody help me to sort this out, as I am trying it for weeks?

Not understand doc

Sorry I can't really understand

# install node core shims and recursively hack package.json files
# in ./node_modules to add/update the "browser"/"react-native" field with relevant mappings
./node_modules/.bin/rn-nodeify --hack --install

after npm i --save-dev tradle/rn-nodeify i stuck

Missing crypto error even after following install steps

I have done the installation. After installation, I have node_modules/react-native-crypto folder but no node_modules/crypto folder. Is this normal? I'm trying to use PubNub within react-native and I believe PubNub is dependent on crypto.

This is the error I get when I run react-native log-android:

$ react-native log-android
Starting the logger (C:\Users\arvindpdmn\AppData\Local\Android\Sdk/platform-tools/adb logcat *:S ReactNative:V ReactNativeJS:V)...
--------- beginning of main
I/ReactNativeJS(23499): Running application "BluetoothSerialExample" with appParams: {"initialProps":{},"rootTag":1}. __DEV__ === true, development-level warning are ON, performance optimizations are OFF
I/ReactNativeJS(24886): Running application "BluetoothSerialExample" with appParams: {"initialProps":{},"rootTag":1}. __DEV__ === true, development-level warning are ON, performance optimizations are OFF
E/ReactNativeJS(  464): Requiring unknown module "crypto".If you are sure the module is there, try restarting the packager or running "npm install".
E/ReactNativeJS(  464): Module AppRegistry is not a registered callable module.
E/ReactNativeJS( 1439): Requiring unknown module "crypto".If you are sure the module is there, try restarting the packager or running "npm install".
E/ReactNativeJS( 1439): Module AppRegistry is not a registered callable module.
--------- beginning of system
E/ReactNativeJS( 3598): Requiring unknown module "crypto".If you are sure the module is there, try restarting the packager or running "npm install".
E/ReactNativeJS( 3598): Module AppRegistry is not a registered callable module.

Error secure random number generation not supported by this browser use chrome, FireFox or Internet Explorer 1

Hi.
I use 'crypto.publicEncrypt' in my code RN. Android test, release and Ios test word good, but IOS release error 'Error secure random number generation not supported by this browser use chrome, FireFox or Internet Explorer 1'

System:
React-native-cli: 2.0.1
React-native: 0.61.5
Node: v12.11.1

My code:
RNRandomBytes.randomBytes(24, (err, bytes) => {
const randomAESkey = bytes
const sha256Pass = CryptoJS.HmacSHA256(password, Config.SHARE_KEY)
const key = CryptoJS.enc.Base64.parse(randomAESkey)
let iv = new Buffer(randomAESkey, 'base64').slice(0, 16).toString('base64')
iv = CryptoJS.enc.Base64.parse(iv)
const aes256Pass = CryptoJS.AES.encrypt(sha256Pass, key, { iv: iv, mode: CryptoJS.mode.CBC, })
const deviceId = DeviceInfo.getUniqueId()
const RSA_PKCS1_PADDING = 1
console.log('Buffer.from(randomAESkey) ', Buffer.from(randomAESkey))
const enc = crypto.publicEncrypt( --> Begin error
{
key: Config.APP_PUBLIC_KEY,
padding: RSA_PKCS1_PADDING,
},
Buffer.from(randomAESkey),
)
const data = {
Password: aes256Pass.toString(),
UserName: (registerOrLoginState && registerOrLoginState.Phone) || '',
IsProvideKey: true,
Imei: deviceId,
EncryptKey: enc.toString('base64'),
SessionId: '',
DeviceType: Platform.OS.toUpperCase(),
}
}

Slice method returns the original data

const hash = Crypto.createHash('sha256');
const key = hash.update("pony 2019").digest();
console.log('ๅˆ†ๅ‰ฒๅ‰้•ฟๅบฆ>>>', key.length); // 32 length
const skey = key.slice(0, 5);
console.log('ๅˆ†ๅ‰ฒๅŽ้•ฟๅบฆ>>>', skey.length); // 32 length

JavaCompile error

react-native-version: 0.60.5
java: 8

react-native run-android doesn't build by throwing the following error

**> Configure project :react-native-webview
:react-native-webview:reactNativeAndroidRoot C:\Users\karth\Desktop\Nvest\gxwallet-cli\node_modules\react-native\android

Task :react-native-os:compileDebugJavaWithJavac FAILED

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.4.1/userguide/command_line_interface.html#sec:command_line_warnings
48 actionable tasks: 8 executed, 40 up-to-date
C:\Users\karth\Desktop\Nvest\gxwallet-cli\node_modules\react-native-os\android\src\main\java\com\peel\react\RNOSModule.java:31: error: method does not override or implement a method from a supertype
@OverRide
^
1 error

FAILURE: Build failed with an exception.**

Problem with ECDH keypair generation

Hi, I recently encountered a problem with ECDH initialization.
I used the following code:

const ecdh = crypto.createECDH('secp521r1');
const publicKey = ecdh.generateKeys();

however it produces an error

Error: Not implemented yet

I traced the error back to the 'elliptic' lib that uses 'brorand' lib for rand numbers, which contains some old code that throws this error...

I want to ask, whether anybody tried this functionality, and if so, was it working properly?

Thanks.

Got create-hmac module can not resolve error

Followed the setting step. but when import shim.js. Got error.

This is index.ios.js


import React, { Component } from 'react';
import './shim.js'

import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';



export default class SnowflakePersonlized extends Component {
  render() {

/*
      var bcrypt = require('js-base64');
      const encoded2=bcrypt.encode('a');
      console.log("encoded1"+encoded1);
*/

      return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
        </Text>
        <Text style={styles.instructions}>
        </Text>
        <Text style={styles.instructions}>
          Press Cmd+R to reload,{'\n'}
          Cmd+D or shake for dev menu
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('SnowflakePersonlized', () => SnowflakePersonlized);

This is generated shim.js file:

if (typeof __dirname === 'undefined') global.__dirname = '/'
if (typeof __filename === 'undefined') global.__filename = ''
if (typeof process === 'undefined') {
  global.process = require('process')
} else {
  const bProcess = require('process')
  for (var p in bProcess) {
    if (!(p in process)) {
      process[p] = bProcess[p]
    }
  }
}

process.browser = false
if (typeof Buffer === 'undefined') global.Buffer = require('buffer').Buffer

// global.location = global.location || { port: 80 }
const isDev = typeof __DEV__ === 'boolean' && __DEV__
process.env['NODE_ENV'] = isDev ? 'development' : 'production'
if (typeof localStorage !== 'undefined') {
  localStorage.debug = isDev ? '*' : ''
}

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
  }
}

screen shot 2017-01-12 at 00 59 01

PREDICTABLE RANDOM NUMBER GENERATOR [Security issue]

Issue:
The mobile application uses a predictable Random Number Generator (RNG).
Under certain conditions this weakness may jeopardize mobile application data encryption or other protection based on randomization. For example,
if encryption tokens are generated inside of the application and an attacker can provide application with a predictable token to validate and then
execute a sensitive activity within the application or its backend.

Reference:

Can you help if this is related to crypto randomBytes function?

error: bundling failed: Error: EISDIR: illegal operation on a directory

I followed the installation directions given for react-native-crypto and update request's crypto calls to:
import crypto from 'react-native-crypto';

With that being said, I am running into the error in the title when I try to use the package depending on request.

I'm pretty green in this area, so I could be doing something wrong. Any thoughts?

Using ReactNativify instead of rn-nodeify?

Using react-native-crypto requires rn-nodeify, but on that project README it describes itself as a hack and states:

If you're looking for a saner approach, check out ReactNativify. I haven't tested it myself, but I think philikon will be happy to help.

So my question is: Can we use react-native-crypto this way as well?

ReactNativify code uses crypto-browserify at the moment and in global.js does not offer an example of shimming getRandomValues for use in production.
Changing the crypto: 'crypto-browserify' in babelrc transformer.js crytpo: 'react-native-crypto' on its own doesn't cut it.

I see react-native-crypto generates a bunch of shim code. Maybe be some of that needs to added?

I have asked a similar question on the ReactNativify project: philikon/ReactNativify#10

Thank you.

PS I have also posted this on stackoverflow: https://stackoverflow.com/q/45301900/8295283

Odd shim file being generated?

After adding this library, and using it like this:

"postinstall": "rn-nodeify --install stream,crypto --hack"

I'm seeing some odd behavior with the shim.js that is generated. This is generated, and the original version of random-bytes is still used by all of my dependencies.

if (typeof __dirname === 'undefined') global.__dirname = '/'
if (typeof __filename === 'undefined') global.__filename = ''
if (typeof process === 'undefined') {
  global.process = require('process')
} else {
  var bProcess = require('process')
  for (var p in bProcess) {
    if (!(p in process)) {
      process[p] = bProcess[p]
    }
  }
}

process.browser = false
if (typeof Buffer === 'undefined') global.Buffer = require('buffer').Buffer

// global.location = global.location || { port: 80 }
var isDev = typeof __DEV__ === 'boolean' && __DEV__
process.env['NODE_ENV'] = isDev ? 'development' : 'production'
if (typeof localStorage !== 'undefined') {
  localStorage.debug = isDev ? '*' : ''
}

Searching through these issues, I found that most developers end up with this shim.js file:

if (typeof __dirname === 'undefined') global.__dirname = '/'
if (typeof __filename === 'undefined') global.__filename = ''
if (typeof process === 'undefined') {
  global.process = require('process')
} else {
  var bProcess = require('process')
  for (var p in bProcess) {
    if (!(p in process)) {
      process[p] = bProcess[p]
    }
  }
}

process.browser = false
if (typeof Buffer === 'undefined') global.Buffer = require('buffer').Buffer

// global.location = global.location || { port: 80 }
var isDev = typeof __DEV__ === 'boolean' && __DEV__
process.env['NODE_ENV'] = isDev ? 'development' : 'production'
if (typeof localStorage !== 'undefined') {
  localStorage.debug = isDev ? '*' : ''
}

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
  }
}

If I just use the second file as my shim file, everything works and it properly replaces getRandomValues on crypto. Am I missing something with how rn-nodeify works?

Thanks!

how to verify JSON object in react native

Hi,
I am using RN version 0.45.1,
And I am trying to write an application in React Native which receives data in JSON format and I want to add digital signature to data in order to verify the message.
currently I am only interested in the application side, meaning - only the verification of the data.
The data, json object, is stored in Amazon S3 and I am planning to sign it with online tool for now.

how can I do this?

Thanks,

Last step in react-native-crypto script breaks project


# install node core shims and recursively hack package.json files
# in ./node_modules to add/update the "browser"/"react-native" field with relevant mappings
./node_modules/.bin/rn-nodeify --hack --install

This is a pretty hacky solution and I'm pretty sure does not work with react-native 0.56.0 but because of a lack of explanation of what is actually being done in this script combined with react native's always anonymous async bridging it's pretty tough to know what happened, how my project was changed by the script, how I could reverse it, trouble shooting, ect. I am also not the only one who has written issues pointing this out. Thank you very much for this project I'd love to do what I can to help others use it as well.

For my example use case I followed the exact instructions, no shims.js file was created, and I am left not knowing where to go from there.
edit: Now after having written this I have found the nodeify module and am reading up on it, and will search through the issue list for related.

Problem installing the package

Hi, I tried to install the package. I followed all tricks I could fould, even the "fix" from 9917779, but running the app always fails on error

"undefined is not an object (evaluating 'process.version.split')"

Any ideas what to do?

React Native arguably does a resolve.alias equivalent a la webpack now

In the README, it says that "react-native doesn't currently have a resolve.alias a la webpack".

Would you say that the extraNodeModules setting in metro.config.js counts as similar enough feature that achieves what you need?

module.exports = {
  resolver: {
    extraNodeModules: {
      crypto: require('react-native-crypto'),
    },
  },
};

(Source)

Error: Invariant failed: Browser history needs a DOM

I'm getting this error when I import ./shim.js as the first line in my component. I'm not sure why that file has the last line commented out:

// require('crypto')

but I've uncommented it since that's actually what I'm installing this package for. any idea why I'm getting this and how to fix it?

in fact, it's the uncommenting of that line that causes the problem

Failed to compile upon adding on react native 0.60

I got the following error:

error: method does not override or implement a method from a supertype
    @Override
    ^
1 error

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':react-native-os:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 32s

    at checkExecSyncError (child_process.js:629:11)
    at execFileSync (child_process.js:647:13)
    at runOnAllDevices (D:\_crypto-defense-source-codes\Zynesis\nzia-wallet\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:74:39)
    at buildAndRun (D:\_crypto-defense-source-codes\Zynesis\nzia-wallet\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:158:41)
    at then.result (D:\_crypto-defense-source-codes\Zynesis\nzia-wallet\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:125:12)
    at process._tickCallback (internal/process/next_tick.js:68:7)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] android: `react-native run-android`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] android script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\hansy\AppData\Roaming\npm-cache\_logs\2019-09-17T04_03_57_096Z-debug.log

generateKeyPairSync is not function

i have a demo to using the library

node v12.7.0
react-native v0.59.9

i have install the library, and it can work well as following

 componentDidMount(){
    console.log(crypto.getHashes());
    crypto.generateKeyPairSync();
  }

crypto.getHashes() can work.
but generateKeyPairSync() hints not a function.

can anyone give me a help:)

Install only required rn-nodeify dependencies

rn-nodeify --install --hack from readme installs all rn-nodeify modules. Is it possible to provide a list of packages, that are only required for react-native-crypto?
For example rn-nodeify --install "process, react-native-randombytes" --hack

createCipheriv support

There is no createCipheriv method in this library while there is in the Node.js one..
Firstly, is the support planned?
Secondly, I have a special use case, where the iv is an empty string. Can I accomplish that somehow with the existing methods?

Cant even compile react-native-crypto using ts

`error Cannot use import statement outside a module. Run CLI with --verbose flag for more details node_modules/react-native-crypto/index.js:3
import { randomBytes } from 'react-native-randombytes'

^^^^^^
`
"react-native": "0.62.2",
"typescript": "^3.8.3"

pod install

the README states that after installation of randombytes, the user should do:

# react-native link react-native-randombytes

but I believe that is outdated. unless I'm wrong I need to do instead:

cd ios && pod install

but when I do, it pukes:

[!] CocoaPods could not find compatible versions for pod "ReactCommon/jscallinvoker":
In snapshot (Podfile.lock):
ReactCommon/jscallinvoker (from ../node_modules/react-native/ReactCommon)

In Podfile:
ReactCommon/jscallinvoker (from ../node_modules/react-native/ReactCommon)

None of your spec sources contain a spec satisfying the dependency: ReactCommon/jscallinvoker (from ../node_modules/react-native/ReactCommon).

You have either:

  • out-of-date source repos which you can update with pod repo update or with pod install --repo-update.
  • mistyped the name or version.
  • not added the source repo that hosts the Podspec to your Podfile.

which I believe is related to installation of this package since I didn't have the problem before I installed. for context, this is being installed on an RN Expo project with RN v0.62.1

Question: run rn-nodeify --install with mandatory package only

Hi !

A quick question,
When doing rn-nodeify --install --hack, I suspect it installs much more packages than actually needed to for react-native-crypto. I Might be wrong thought... Anyway, if this is the case, has someone the list of the mandatory packages to make all features of react-native-crypto work ?

Thanks !

iOS TypeError: undefined is not an object (evaluating 'sjcl.random')

RN 0.39.2, node 7.x, using Remote Debugger, TypeError: undefined is not an object (evaluating 'sjcl.random') when running synchronous randomBytes call. When running it asynchronous, the output is null from the async call, though it does return the async call.

Found out that the Safari remote debugger does not work, due to the "error getting entropy from browser". But that it DOES work on the device. Maybe put this in the readme or output a more friendly error message to browser console.

Failed to match tag: "int" at: ["modulus"]

Hi, @mvayngrib
There is an tricky bug with publicEncrypt function.

I deep into the source code to debug at ~/node_modules/asn1.js/lib/asn1/decoders/der.js file. I got error at line

image

And error throw out the screen like this
image

But, when I comment this block code (by pass that check). My code will work as a charm. I did not know about that validate for? Could you explain for me about that?

typerror null is not an object RNRandombytes.seed - iOS

Integrated react-native-crypto to a react-native project.
Project is working fine in Android but for iOS getting the below error
"typerror null is not an object RNRandombytes.seed"

package.json
"scripts": { "android": "react-native run-android", "ios": "react-native run-ios", "start": "react-native start", "test": "jest", "lint": "eslint .", "postinstall": "rn-nodeify --install crypto,process,stream,events --hack" }, "dependencies": {, "crypto-js": "3.1.9-1", "events": "^1.0.0", "process": "^0.11.0", "react": "16.11.0", "react-native": "0.62.2", "react-native-crypto": "^2.2.0", "react-native-randombytes": "^3.5.3",] "readable-stream": "1.0.33", "stream-browserify": "^1.0.0", "vm-browserify": "0.0.4" }, "devDependencies": { "@babel/core": "7.9.6", "@babel/runtime": "7.9.6", "@react-native-community/eslint-config": "0.0.5", "babel-jest": "24.9.0", "eslint": "6.8.0", "jest": "24.9.0", "metro-react-native-babel-preset": "0.58.0", "react-test-renderer": "16.11.0", "rn-nodeify": "^10.2.0" },

UdpSocketsModule and TcpSocketsModule does not exist

Hi @mvayngrib,
Thanks for your efforts. But, I got this error after install and link react-native-crypto. Maybe UdpSocketsModuleand TcpSocketsModuledoes not exist.

\MainActivity.java:5: error: package com.tradle.react does not exist
import com.tradle.react.UdpSocketsModule;

\MainActivity.java:6: error: package com.peel.react does not exist
import com.peel.react.TcpSocketsModule;    

and this is my stacktrace when I run debug

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileDebugJavaWithJavac'.
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
        at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.api.internal.AbstractTask.executeWithoutThrowingTaskFailure(AbstractTask.java:310)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTask(AbstractTaskPlanExecutor.java:79)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:63)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:51)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:23)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:88)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
        at org.gradle.execution.DefaultBuildExecuter.access$200(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter$2.proceed(DefaultBuildExecuter.java:68)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:55)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:86)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:90)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:28)
        at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:50)
        at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:27)
        at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:40)
        at org.gradle.internal.Actions$RunnableActionAdapter.execute(Actions.java:169)
        at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:237)
        at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:210)
        at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:35)
        at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:24)
        at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:206)
        at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:169)
        at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33)
        at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22)
        at org.gradle.launcher.Main.doAction(Main.java:33)
        at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45)
        at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:54)
        at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:35)
        at org.gradle.launcher.GradleMain.main(GradleMain.java:23)
        at org.gradle.wrapper.BootstrapMainStarter.start(BootstrapMainStarter.java:30)
        at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:127)
        at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
Caused by: org.gradle.api.internal.tasks.compile.CompilationFailedException: Compilation failed; see the compiler error output for details.
        at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:47)
        at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:33)
        at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.delegateAndHandleErrors(NormalizingJavaCompiler.java:101)
        at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:50)
        at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:36)
        at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:34)
        at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:25)
        at org.gradle.api.tasks.compile.JavaCompile.performCompilation(JavaCompile.java:157)
        at org.gradle.api.tasks.compile.JavaCompile.compile(JavaCompile.java:137)
        at org.gradle.api.tasks.compile.JavaCompile.compile(JavaCompile.java:91)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.doExecute(AnnotationProcessingTaskFactory.java:243)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:219)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.execute(AnnotationProcessingTaskFactory.java:230)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:208)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)

_Stats.default is not a constructor

image

here is my code:

import React,{Component} from 'react';
import {View,Text,TextInput,ScrollView,Image} from 'react-native';
import { Icon } from 'react-native-elements';
import YTSearch from 'youtube-api-search';
import styles from './StatsStyle';
import VideoList from '../SearchFolder/VideoList';
import VideoListItem from '../SearchFolder/VideoListItem';

const API_KEY = ' '; // hided for github ;
var query = '';
export default class StatsScreen extends Component
{

constructor(props)
{
super(props);

this.state = {
   term: '',
   imgLink: '',
   width: 0,
   height: 0,
   title: '',
   totalViews: 0,
   totalSubs: 0,
   totalVideos: 0 ,
   channelId : '' ,
   url: '',
   videos: [],
   loading: false,
}

};

searchYT = term =>
{
this.setState({loading: true});
YTSearch({key: API_KEY, term } ,videos =>
{
this.setState({
loading: false,
videos
});
});
}

onChangeText = term =>
{
this.searchYT(term);
}

getChannelId = a => {
var url = 'https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=1&q='+ a +'&key=AIzaSyBvN3k86aUPjuRt8S6FDUlG5fGg96lPWlo';
return fetch(url)
.then((response) => response.json())
.then((data) => {
a = data.items[0].snippet.channelId;
return a;
})
.catch((error) => {
console.error(error);
});
};

fetchData = data => {
var foo = data.items[0].snippet.thumbnails.default.url;
var flag = data.items[0].statistics;
console.log('this is fetchData',data.items[0].statistics.subscriberCount);

  this.setState({imgLink: foo, width:foo.width,height:foo.height,title:data.items[0].snippet.title, totalSubs:flag.subscriberCount,totalViews:flag.viewCount,totalVideos:foo.videoCount});

  console.log('llllll',this.state.imgLink);
  return 1;

}

updateSubscribers = response =>
{
this.setState({totalSubs: response.items[0].statistics.subscriberCount});
}

onPressedButton = channelId =>
{
// fetch the value entered in the input field
//alert(channelId);
//fetch the value(channelId) that is enter in the input field
// make a request
var url = 'https://www.googleapis.com/youtube/v3/channels?key='+API_KEY+'&id=' + channelId + '&part=snippet,contentDetails,statistics';
this.setState({url: url});
return fetch(url)
.then((response) =>
{
return response.json();
console.log("popo",response);
})
// fetchData(data);
.then((data) => {
this.fetchData(data);
console.log('lol',this.state.imgLink);
console.log('hello',this.state);
})
.catch((error) => {
console.log(error);
})
//now fetching the response from the yt api again and again
.setInterval(() =>
{
var url = 'https://www.googleapis.com/youtube/v3/channels?key='+API_KEY+'&id=' + channelId + '&part=statistics';
return fetch(url)
.then((response) =>
{
return response.json()
})
.then((data) => {
this.updateSubscribers(data)
},0)

.catch((error) => {
console.log(error);
});
});
}

render()
{
let{imgLink,totalSubs,totalViews,totalVideos,width,height,title,channelId,videos,loading,term} = this.state;
return(

<View style = {styles.top}>

    <TextInput style = {styles.searchBox}
     placeholder = 'Search here...'
     value = {this.state.term}
     onChangeText = {term => {
       this.setState({term});/// {term} = term
       this.onChange({ term })
     }}
     />

    <Icon style = {styles.icon}
    name = 'search'
    type = 'material'
    color= 'black'
    onPress = {() => {
      console.log('this is term ',this.state.term);
     this.getChannelId(this.state.term)
     .then((data) => {
      onPressedButton(data);
    });
    }
  }
        />
        <VideoList videos = {videos} style = {styles.videoList}/>
</View>

{title}

<Text style = {{fontSize: 40,fontWeight: 'bold'}}>Subscribers
{totalSubs}

<Text style = {{fontSize: 40,fontWeight: 'bold'}}>TotalViews
{totalViews}

<Text style = {{fontSize: 40,fontWeight: 'bold'}}>TotalVideos
{totalVideos}

);
}
}

Require cycle

When I run my react native app I have a warning:
Require cycle: node_modules/react-native-crypto/index.js -> node_modules/react-native-randombytes/index.js -> node_modules/sjcl/sjcl.js -> node_modules/react-native-crypto/index.js

My .babelrc:

{
  "presets": ["module:metro-react-native-babel-preset"],
  "sourceMaps": true,
  "plugins": [
    ["babel-plugin-rewrite-require", {
      "aliases": {
        "crypto": "react-native-crypto",
        "http": "http-browserify",
        "https": "https-browserify",
        "os": "os-browserify",
        "stream": "stream-browserify",
        "vm": "vm-browserify"
      }
    }]
  ]
}

It looks like sjcl.js require crypto module which is replaced by react-native-crypto. Is there any methods how to avoid it?

Have errors with build.

Good morning!

Build troubles with macOS.
Installed like this:

react-native init simplepr;
cd simplepr;
npm i --save react-native-crypto;
npm i --save react-native-randombytes;
# react-native link react-native-randombytes --- create error 
# "React Native CLI uses autolinking for native-depencies"
npm i --save-dev rn-nodeify@latest;
./node_modules/.bin/rn-nodeify --hack --install;

After this

cd ios;
pod install;
cd ..;

Adding in index.js:

import './shim.js';

and adding in App.js:

import crypto from 'crypto';
console.log(crypto.createHash('sha256').update('hell').digest('hex'));

Run react-native run-ios and have linker error:


Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65.

...

The following commands failed:
Ld *path to app*

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.