@maximai/maxim-js
Version:
Maxim AI JS SDK. Visit https://getmaxim.ai for more info.
74 lines • 2.69 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSecureRandomBytesAsync = getSecureRandomBytesAsync;
exports.getRandomBytes = getRandomBytes;
exports.isSecureRandomAvailable = isSecureRandomAvailable;
exports.getSecureRandomHexAsync = getSecureRandomHexAsync;
exports.getRandomHex = getRandomHex;
const platform_1 = require("../platform");
/**
* Secure random number generation utilities that work across platforms.
* On React Native, will use expo-crypto when available for better security.
* Falls back to platform-appropriate alternatives when needed.
*/
/**
* Generate cryptographically secure random bytes asynchronously.
* Preferred method on React Native when expo-crypto is available.
*
* @param size Number of bytes to generate
* @returns Promise resolving to secure random bytes
*/
async function getSecureRandomBytesAsync(size) {
if (platform_1.platform.crypto.randomBytesAsync) {
return platform_1.platform.crypto.randomBytesAsync(size);
}
// Fallback to sync version
return platform_1.platform.crypto.randomBytes(size);
}
/**
* Generate random bytes synchronously.
* On React Native without expo-crypto, this uses Math.random (less secure).
* Use getSecureRandomBytesAsync() when possible for better security.
*
* @param size Number of bytes to generate
* @returns Random bytes (secure on Node.js, less secure on RN without expo-crypto)
*/
function getRandomBytes(size) {
return platform_1.platform.crypto.randomBytes(size);
}
/**
* Check if secure random number generation is available on the current platform.
*
* @returns True if cryptographically secure RNG is available
*/
function isSecureRandomAvailable() {
var _a;
return (_a = platform_1.platform.crypto.isSecureRandomAvailable) !== null && _a !== void 0 ? _a : true;
}
/**
* Generate a cryptographically secure random hex string.
*
* @param length Length of the hex string (will use length/2 random bytes)
* @returns Promise resolving to hex string
*/
async function getSecureRandomHexAsync(length) {
const bytes = await getSecureRandomBytesAsync(Math.ceil(length / 2));
return Array.from(bytes)
.map(b => b.toString(16).padStart(2, '0'))
.join('')
.slice(0, length);
}
/**
* Generate a random hex string synchronously.
*
* @param length Length of the hex string (will use length/2 random bytes)
* @returns Hex string
*/
function getRandomHex(length) {
const bytes = getRandomBytes(Math.ceil(length / 2));
return Array.from(bytes)
.map(b => b.toString(16).padStart(2, '0'))
.join('')
.slice(0, length);
}
//# sourceMappingURL=secureRandom.js.map