Skip to content

Instantly share code, notes, and snippets.

@mukaschultze
Created November 21, 2023 18:46
Show Gist options
  • Save mukaschultze/26247d4e3652655ae5da4acb73549899 to your computer and use it in GitHub Desktop.
Save mukaschultze/26247d4e3652655ae5da4acb73549899 to your computer and use it in GitHub Desktop.
NativeScript Polyfiils
import { isAndroid } from '@nativescript/core';
class TypeMismatchError extends Error {}
class QuotaExceededError extends Error {}
/**
* @param {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Uint8ClampedArray} array
*/
function getRandomValues(array) {
if (
!(
array instanceof Int8Array ||
array instanceof Uint8Array ||
array instanceof Int16Array ||
array instanceof Uint16Array ||
array instanceof Int32Array ||
array instanceof Uint32Array ||
array instanceof Uint8ClampedArray
)
) {
throw new TypeMismatchError('Expected an integer array');
}
if (array.byteLength > 65536) {
throw new QuotaExceededError('Can only request a maximum of 65536 bytes');
}
if (isAndroid) {
const bytes = java.nio.ByteBuffer.allocate(array.byteLength).array();
java.security.SecureRandom.getInstanceStrong().nextBytes(bytes);
array.set(bytes);
return array;
} else {
SecRandomCopyBytes(kSecRandomDefault, array.byteLength, array as unknown as interop.Pointer);
return array;
}
}
if (typeof global.crypto !== 'object') {
global.crypto = {};
}
if (typeof global.crypto.getRandomValues !== 'function') {
global.crypto.getRandomValues = getRandomValues;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment