react-native-quick-crypto
Version:
A fast implementation of Node's `crypto` module written in C/C++ JSI
81 lines (78 loc) • 2.93 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.hkdf = hkdf;
exports.hkdfDeriveBits = hkdfDeriveBits;
exports.hkdfSync = hkdfSync;
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('Hkdf');
}
return native;
}
function validateCallback(callback) {
if (callback === undefined || typeof callback !== 'function') {
throw new Error('No callback provided to hkdf');
}
}
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 hkdf(digest, key, salt, info, keylen, callback) {
validateCallback(callback);
try {
const normalizedDigest = (0, _utils.normalizeHashName)(digest);
const sanitizedKey = sanitizeInput(key, 'Key');
const sanitizedSalt = sanitizeInput(salt, 'Salt');
const sanitizedInfo = sanitizeInput(info, 'Info');
if (keylen < 0) {
throw new TypeError('Bad key length');
}
const nativeMod = getNative();
nativeMod.deriveKey(normalizedDigest, sanitizedKey, sanitizedSalt, sanitizedInfo, keylen).then(res => {
callback(null, _reactNativeBuffer.Buffer.from(res));
}, err => {
callback(err);
});
} catch (err) {
callback(err);
}
}
function hkdfSync(digest, key, salt, info, keylen) {
const normalizedDigest = (0, _utils.normalizeHashName)(digest);
const sanitizedKey = sanitizeInput(key, 'Key');
const sanitizedSalt = sanitizeInput(salt, 'Salt');
const sanitizedInfo = sanitizeInput(info, 'Info');
if (keylen < 0) {
throw new TypeError('Bad key length');
}
const nativeMod = getNative();
const result = nativeMod.deriveKeySync(normalizedDigest, sanitizedKey, sanitizedSalt, sanitizedInfo, keylen);
return _reactNativeBuffer.Buffer.from(result);
}
function hkdfDeriveBits(algorithm, baseKey, length) {
const hash = algorithm.hash;
const salt = algorithm.salt;
const info = algorithm.info;
// Check if key is extractable or we can access its handle/buffer
// For raw keys, we can export.
const keyBuffer = baseKey.keyObject.export();
// length is in bits, native expects bytes
const keylen = Math.ceil(length / 8);
const hashName = typeof hash === 'string' ? hash : hash.name;
const normalizedDigest = (0, _utils.normalizeHashName)(hashName);
const nativeMod = getNative();
const result = nativeMod.deriveKeySync(normalizedDigest, (0, _utils.binaryLikeToArrayBuffer)(keyBuffer), (0, _utils.binaryLikeToArrayBuffer)(salt), (0, _utils.binaryLikeToArrayBuffer)(info), keylen);
return result;
}
//# sourceMappingURL=hkdf.js.map