get-random-values-polypony
Version:
Synchronous randombytes function that works in node, the browser & react-native!
6 lines • 1.9 kB
JavaScript
const base=window.crypto,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"),entropyFromUUID=require("./entropyFromUUID.js"),nativeModule="GetRandomValuesPolyPony"in rn.NativeModules&&rn.NativeModules.GetRandomValuesPolyPony,uniModules=rn.NativeModules.NativeUnimoduleProxy;let seed;if(nativeModule)seed=nativeModule.newUUID();else{const expoConstants=uniModules&&uniModules.modulesConstants&&uniModules.modulesConstants.ExponentConstants;if(seed=expoConstants&&expoConstants.sessionId,"string"!=typeof seed)throw new Error("Creating Random Seed: No Entropy available to setup random bytes")}if(impl=require("./createRandomSeed.js")(entropyFromUUID(seed)),!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,random=uniMethods&&uniMethods.ExpoRandom&&uniMethods.ExpoRandom.find(method=>"getRandomBase64StringAsync"===method.name)&&function(...args){return uniModules.callMethod("ExpoRandom","getRandomBase64StringAsync",args)};random?random(32).then(bytes=>impl.increaseEntropy(bytes),err=>console.warn(`[WARNING] Error received when looking for strong entropy, using pretty-strong entropy: ${err}`)):console.warn("[WARNING] No means to retreive very strong entropy, using pretty-strong entropy.")}}impl.polyfill=function(){"crypto"in window||(window.crypto={}),"getRandomValues"in window.crypto||(window.crypto.getRandomValues=require("./browserLimitations.js")(impl))},module.exports=impl;