UNPKG

react-native-quick-crypto

Version:

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

51 lines (50 loc) 1.72 kB
"use strict"; import { NativeQuickCrypto } from './NativeQuickCrypto/NativeQuickCrypto'; import { lazyDOMException, validateFunction } from './Utils'; import { kAesKeyLengths } from './aes'; import { SecretKeyObject } from './keys'; export const generateKeyPromise = (type, options // | HmacKeyGenParams ) => { return new Promise((resolve, reject) => { generateKey(type, options, (err, key) => { if (err) { reject([err, undefined]); } resolve([undefined, key]); }); }); }; export const generateKey = (type, options, callback) => { validateLength(type, options.length); if (!validateFunction(callback)) { throw lazyDOMException('Callback is not a function', 'SyntaxError'); } NativeQuickCrypto.webcrypto.generateSecretKey(options.length).then(handle => { callback(undefined, new SecretKeyObject(handle)); }).catch(err => { callback(err, undefined); }); }; export const generateKeySync = (type, options // | HmacKeyGenParams, ) => { validateLength(type, options.length); const handle = NativeQuickCrypto.webcrypto.generateSecretKeySync(options.length); return new SecretKeyObject(handle); }; const validateLength = (type, length) => { switch (type) { case 'aes': if (!kAesKeyLengths.includes(length)) { throw lazyDOMException('AES key length must be 128, 192, or 256 bits', 'OperationError'); } break; case 'hmac': if (length < 8 || length > 2 ** 31 - 1) { throw lazyDOMException('HMAC key length must be between 8 and 2^31 - 1', 'OperationError'); } break; default: throw new Error(`Unsupported key type '${type}' for generateKey()`); } }; //# sourceMappingURL=keygen.js.map