react-native-quick-crypto
Version:
A fast implementation of Node's `crypto` module written in C/C++ JSI
98 lines (97 loc) • 2.59 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.scrypt = scrypt;
exports.scryptSync = scryptSync;
var _reactNativeBuffer = require("@craftzdog/react-native-buffer");
var _reactNativeNitroModules = require("react-native-nitro-modules");
var _utils = require("./utils");
// Lazy load native module
let native;
function getNative() {
if (native == null) {
native = _reactNativeNitroModules.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 (0, _utils.binaryLikeToArrayBuffer)(input);
} catch {
throw new Error(`${name} must be a string, a Buffer, a typed array, or a DataView`);
}
}
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, _reactNativeBuffer.Buffer.from(res));
}, err => {
cb(err);
});
} catch (err) {
cb(err);
}
}
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 _reactNativeBuffer.Buffer.from(result);
}
//# sourceMappingURL=scrypt.js.map