UNPKG

react-native-quick-crypto

Version:

A fast implementation of Node's `crypto` module written in C/C++ JSI

93 lines (92 loc) 2.4 kB
"use strict"; import { Buffer } from '@craftzdog/react-native-buffer'; import { NitroModules } from 'react-native-nitro-modules'; import { binaryLikeToArrayBuffer } from './utils'; // Lazy load native module let native; function getNative() { if (native == null) { native = NitroModules.createHybridObject('Scrypt'); } return native; } const defaults = { N: 16384, r: 8, p: 1, maxmem: 32 * 1024 * 1024 }; function getScryptParams(options) { const N = options?.N ?? options?.cost ?? defaults.N; const r = options?.r ?? options?.blockSize ?? defaults.r; const p = options?.p ?? options?.parallelization ?? defaults.p; const maxmem = options?.maxmem ?? defaults.maxmem; return { N, r, p, maxmem }; } function validateCallback(callback) { if (callback === undefined || typeof callback !== 'function') { throw new Error('No callback provided to scrypt'); } } function sanitizeInput(input, name) { try { return binaryLikeToArrayBuffer(input); } catch { throw new Error(`${name} must be a string, a Buffer, a typed array, or a DataView`); } } export function scrypt(password, salt, keylen, options, callback) { let cb; let opts; if (typeof options === 'function') { cb = options; opts = undefined; } else { cb = callback; opts = options; } validateCallback(cb); try { const { N, r, p, maxmem } = getScryptParams(opts); const sanitizedPassword = sanitizeInput(password, 'Password'); const sanitizedSalt = sanitizeInput(salt, 'Salt'); if (keylen < 0) { throw new TypeError('Bad key length'); } const nativeMod = getNative(); nativeMod.deriveKey(sanitizedPassword, sanitizedSalt, N, r, p, maxmem, keylen).then(res => { cb(null, Buffer.from(res)); }, err => { cb(err); }); } catch (err) { cb(err); } } export function scryptSync(password, salt, keylen, options) { const { N, r, p, maxmem } = getScryptParams(options); const sanitizedPassword = sanitizeInput(password, 'Password'); const sanitizedSalt = sanitizeInput(salt, 'Salt'); if (keylen < 0) { throw new TypeError('Bad key length'); } const nativeMod = getNative(); const result = nativeMod.deriveKeySync(sanitizedPassword, sanitizedSalt, N, r, p, maxmem, keylen); return Buffer.from(result); } //# sourceMappingURL=scrypt.js.map