-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreact-native.js
71 lines (67 loc) · 2.52 KB
/
react-native.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const base = window.crypto
const MAX_SIZE = 65536
let impl
if (base && base.getRandomValues) {
const min = Math.min // babel bug
// Future proofing!
impl = function getRandomValues (input) {
const n = input.byteLength
if (n <= MAX_SIZE) {
return base.getRandomValues(input)
}
for (let i = 0; i < n; i += MAX_SIZE) {
base.getRandomValues(new Uint8Array(input.buffer, i + input.byteOffset, min(n - i, MAX_SIZE)))
}
return input
}
} else {
const rn = require('react-native')
const entropyFromUUID = require('./entropyFromUUID.js')
const nativeModule = ('GetRandomValuesPolyPony' in rn.NativeModules && rn.NativeModules.GetRandomValuesPolyPony)
const uniModules = rn.NativeModules.NativeUnimoduleProxy
let seed
if (nativeModule) {
seed = nativeModule.newUUID()
} else {
const expoConstants = (uniModules && uniModules.modulesConstants && uniModules.modulesConstants.ExponentConstants)
seed = expoConstants && expoConstants.sessionId
if (typeof seed !== 'string') {
throw new Error('Creating Random Seed: No Entropy available to setup random bytes')
}
}
impl = require('./createRandomSeed.js')(entropyFromUUID(seed))
if (!nativeModule) {
// Collect more entropy since Expo.sessionId can be read from
// other processes quite readily, while nativeModule.newUUID()
// is harder to intercept.
const uniMethods = uniModules && uniModules.exportedMethods
const random = (
uniMethods &&
uniMethods.ExpoRandom &&
uniMethods.ExpoRandom.find(method => method.name === 'getRandomBase64StringAsync') &&
function (...args) {
return uniModules.callMethod('ExpoRandom', 'getRandomBase64StringAsync', args)
}
)
if (random) {
// 8 bytes are enough, but increaseEntropy assumes utf-8 encoded entropy, but
// random returns base64 encoded entropy, which means we loose some entropy in the conversion.
// To counteract ~x4 loss of entropy we collect 32 bit.
random(32).then(
bytes => impl.increaseEntropy(bytes),
err => console.warn(`[WARNING] Error received when looking for strong entropy, using pretty-strong entropy: ${err}`)
)
} else {
console.warn('[WARNING] No means to retreive very strong entropy, using pretty-strong entropy.')
}
}
}
impl.polyfill = function () {
if (!('crypto' in window)) {
window.crypto = {}
}
if (!('getRandomValues' in window.crypto)) {
window.crypto.getRandomValues = require('./browserLimitations.js')(impl)
}
}
module.exports = impl