UNPKG

react-native-quick-crypto

Version:

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

68 lines (61 loc) 2.46 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.hmacImportKey = hmacImportKey; var _reactNativeBuffer = require("@craftzdog/react-native-buffer"); var _keys = require("./keys"); var _Utils = require("./Utils"); async function hmacImportKey(algorithm, format, keyData, extractable, keyUsages) { // Validate key usages if ((0, _Utils.hasAnyNotIn)(keyUsages, ['sign', 'verify'])) { throw (0, _Utils.lazyDOMException)('Unsupported key usage for an HMAC key', 'SyntaxError'); } if (!keyData) { throw (0, _Utils.lazyDOMException)('Invalid keyData', 'DataError'); } let keyMaterial; switch (format) { case 'raw': { // For raw format, keyData should be BufferLike if (typeof keyData === 'string') { keyMaterial = _reactNativeBuffer.Buffer.from(keyData, 'base64'); } else if (_reactNativeBuffer.Buffer.isBuffer(keyData)) { keyMaterial = keyData; } else { keyMaterial = _reactNativeBuffer.Buffer.from(keyData); } break; } case 'jwk': { const jwk = keyData; // Validate required JWK properties if (typeof jwk !== 'object' || jwk.kty !== 'oct' || !jwk.k) { throw (0, _Utils.lazyDOMException)('Invalid JWK format for HMAC key', 'DataError'); } if (algorithm.length === 0) { throw (0, _Utils.lazyDOMException)('Zero-length key is not supported', 'DataError'); } // The Web Crypto spec allows for key lengths that are not multiples of 8. We don't. if (algorithm.length && algorithm.length % 8) { throw (0, _Utils.lazyDOMException)('Unsupported algorithm.length', 'NotSupportedError'); } // Convert base64 to buffer keyMaterial = _reactNativeBuffer.Buffer.from(jwk.k, 'base64'); // If algorithm.length is specified, validate key length if (algorithm.length && keyMaterial.length * 8 !== algorithm.length) { throw (0, _Utils.lazyDOMException)('Invalid key length', 'DataError'); } break; } default: throw (0, _Utils.lazyDOMException)(`Unable to import HMAC key with format ${format}`, 'NotSupportedError'); } // Create the key object const keyObject = (0, _keys.createSecretKey)(keyMaterial); // Return new CryptoKey return new _keys.CryptoKey(keyObject, algorithm, keyUsages, extractable); } //# sourceMappingURL=mac.js.map