@korekoi/react-native-get-random-values
Version:
⚡️ A fast implementation of `crypto.getRandomValues` for React Native
24 lines (23 loc) • 975 B
JavaScript
import { NitroModules } from "react-native-nitro-modules";
const MAX_BYTE_ARRAY_LENGTH = 65536;
const sodium = NitroModules.createHybridObject("Sodium");
// port correct types as the browser/node implementation https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#exceptions
class TypeMismatchError extends Error {
}
class QuotaExceededError extends Error {
}
const getRandomValues = (array) => {
if (array.byteLength > MAX_BYTE_ARRAY_LENGTH) {
throw new QuotaExceededError("ArrayBuffer length exceeds maximum length of 65536 bytes.");
}
sodium.getRandomValues(array.buffer);
return array;
};
if (typeof global.crypto !== "object") {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
global.crypto = {};
}
if (typeof global.crypto.getRandomValues === "undefined") {
global.crypto.getRandomValues = getRandomValues;
}
export { getRandomValues, TypeMismatchError, QuotaExceededError, MAX_BYTE_ARRAY_LENGTH };