UNPKG

js-crypto-aes

Version:

Universal Module for AES Encryption and Decryption in JavaScript

232 lines 12.4 kB
"use strict"; /** * aes.js */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.unwrapKey = exports.wrapKey = exports.decrypt = exports.encrypt = void 0; var util = __importStar(require("js-crypto-env")); var nodeapi = __importStar(require("./nodeapi")); var webapi = __importStar(require("./webapi")); var params_1 = __importDefault(require("./params")); /** * Check if the given algorithm spec is valid. * @param {String} name - Name of the specified algorithm like 'AES-GCM'. * @param {Uint8Array} iv - IV byte array if required * @param {Number} tagLength - Authentication tag length if required * @throws {Error} - Throws if UnsupportedAlgorithm, InvalidArguments, InvalidIVLength, or InvalidTagLength. */ var assertAlgorithms = function (_a) { var name = _a.name, iv = _a.iv, tagLength = _a.tagLength; if (params_1.default.ciphers[name].ivLength) { if (!(iv instanceof Uint8Array)) throw new Error('InvalidArguments'); if (iv.byteLength < 2 || iv.byteLength > 16) throw new Error('InvalidIVLength'); if (params_1.default.ciphers[name].staticIvLength && (params_1.default.ciphers[name].ivLength !== iv.byteLength)) throw new Error('InvalidIVLength'); } if (params_1.default.ciphers[name].tagLength && tagLength) { if (!Number.isInteger(tagLength)) throw new Error('InvalidArguments'); if (tagLength < 4 || tagLength > 16) throw new Error('InvalidTagLength'); } }; /** * Encrypt data with AES * @param {Uint8Array} msg - Message to be encrypted. * @param {Uint8Array} key - The symmetric key used to encrypt the message. * @param {String} [name = 'AES-GCM'] - Name of the specified algorithm like 'AES-GCM'. * @param {Uint8Array} [iv] - Byte array of the initial vector if required. * @param {Uint8Array} [additionalData = new Uint8Array([])] - Byte array of additional data if required. * @param {Number} [tagLength = params.ciphers[name].tagLength] - Authentication tag length if required. * @return {Promise<Uint8Array>} - Encrypted message. * @throws {Error} - Throws if InvalidArguments, FaildToEncryptWeb/Node, or UnsupportedEnvironment (no webcrypto/nodecrypto). */ var encrypt = function (msg, key, _a) { var _b = _a.name, name = _b === void 0 ? 'AES-GCM' : _b, iv = _a.iv, _c = _a.additionalData, additionalData = _c === void 0 ? new Uint8Array([]) : _c, tagLength = _a.tagLength; return __awaiter(void 0, void 0, void 0, function () { var env; return __generator(this, function (_d) { // assertion and sanitizing assertAlgorithms({ name: name, iv: iv, tagLength: tagLength }); if (params_1.default.ciphers[name].tagLength && !tagLength) tagLength = params_1.default.ciphers[name].tagLength; env = util.getCrypto(); if (env.name === 'webCrypto') { // for web API if (typeof env.crypto.importKey !== 'function' || typeof env.crypto.encrypt !== 'function') throw new Error('UnsupportedWebCrypto'); return [2 /*return*/, webapi.encrypt(msg, key, { name: name, iv: iv, additionalData: additionalData, tagLength: tagLength }, env.crypto)]; } else if (env.name === 'nodeCrypto') { // for node return [2 /*return*/, nodeapi.encrypt(msg, key, { name: name, iv: iv, additionalData: additionalData, tagLength: tagLength }, env.crypto)]; } else throw new Error('UnsupportedEnvironment'); // TODO:fallback to native implementation return [2 /*return*/]; }); }); }; exports.encrypt = encrypt; /** * Decrypt data with AES * @param {Uint8Array} data - Byte array of encrypted data. * @param {Uint8Array} key - Byte array of symmetric key to be used for decryption. * @param {String} [name = 'AES-GCM'] - Name of the specified algorithm like 'AES-GCM'. * @param {Uint8Array} [iv] - Byte array of the initial vector if required. * @param {Uint8Array} [additionalData = new Uint8Array([])] - Byte array of additional data if required. * @param {Number} [tagLength = params.ciphers[name].tagLength] - Authentication tag length if required. * @return {Promise<Uint8Array>} - Decrypted plaintext message. * @throws {Error} - Throws if InvalidArguments, FailedToDecryptWeb/Node, or UnsupportedEnvironment (no webcrypto/nodecrypto). */ var decrypt = function (data, key, _a) { var _b = _a.name, name = _b === void 0 ? 'AES-GCM' : _b, iv = _a.iv, _c = _a.additionalData, additionalData = _c === void 0 ? new Uint8Array([]) : _c, tagLength = _a.tagLength; return __awaiter(void 0, void 0, void 0, function () { var env; return __generator(this, function (_d) { // assertion and sanitizing assertAlgorithms({ name: name, iv: iv, tagLength: tagLength }); if (params_1.default.ciphers[name].tagLength && !tagLength) tagLength = params_1.default.ciphers[name].tagLength; env = util.getCrypto(); if (env.name === 'webCrypto') { // for web API if (typeof env.crypto.importKey !== 'function' || typeof env.crypto.decrypt !== 'function') throw new Error('UnsupportedWebCrypto'); return [2 /*return*/, webapi.decrypt(data, key, { name: name, iv: iv, additionalData: additionalData, tagLength: tagLength }, env.crypto)]; } else if (env.name === 'nodeCrypto') { // for node return [2 /*return*/, nodeapi.decrypt(data, key, { name: name, iv: iv, additionalData: additionalData, tagLength: tagLength }, env.crypto)]; } else throw new Error('UnsupportedEnvironment'); return [2 /*return*/]; }); }); }; exports.decrypt = decrypt; /** * AES-KW wrapping * @param keyToBeWrapped {Uint8Array} - key bytes to be wrapped * @param wrappingKey {Uint8Array} - wrapping key encryption key * @param name {'AES-KW'} - this is simply for future extension * @return {Promise<Uint8Array>} - output wrapped key */ var wrapKey = function (keyToBeWrapped, wrappingKey, _a) { var name = _a.name; return __awaiter(void 0, void 0, void 0, function () { var env, iv; return __generator(this, function (_b) { // assertion if (keyToBeWrapped.length % 8 > 0) throw new Error('WrappedKeyMustBeMultipleOf8'); env = util.getCrypto(); iv = (params_1.default.wrapKeys['AES-KW'].defaultIv); if (env.name === 'webCrypto') { // for web API if (typeof env.crypto.importKey !== 'function' || typeof env.crypto.wrapKey !== 'function') throw new Error('UnsupportedWebCrypto'); return [2 /*return*/, webapi.wrapKey(keyToBeWrapped, wrappingKey, { name: name, iv: iv }, env.crypto)]; } else if (env.name === 'nodeCrypto') { // for node return [2 /*return*/, nodeapi.wrapKey(keyToBeWrapped, wrappingKey, { name: name, iv: iv }, env.crypto)]; } else { throw new Error('UnsupportedEnvironment'); // TODO:fallback to native implementation } return [2 /*return*/]; }); }); }; exports.wrapKey = wrapKey; /** * AES-KW unwrapping * @param wrappedKey {Uint8Array} - wrapped key bytes * @param wrappingKey {Uint8Array} - wrapping key encryption key * @param name {'AES-KW'} - this is simply for future extension * @return {Promise<Uint8Array>} - output unwrapped key */ var unwrapKey = function (wrappedKey, wrappingKey, _a) { var name = _a.name; return __awaiter(void 0, void 0, void 0, function () { var env, iv; return __generator(this, function (_b) { env = util.getCrypto(); iv = (params_1.default.wrapKeys['AES-KW'].defaultIv); if (env.name === 'webCrypto') { // for web API if (typeof env.crypto.importKey !== 'function' || typeof env.crypto.unwrapKey !== 'function') throw new Error('UnsupportedWebCrypto'); return [2 /*return*/, webapi.unwrapKey(wrappedKey, wrappingKey, { name: name, iv: iv }, env.crypto)]; } else if (env.name === 'nodeCrypto') { // for node return [2 /*return*/, nodeapi.unwrapKey(wrappedKey, wrappingKey, { name: name, iv: iv }, env.crypto)]; } else { throw new Error('UnsupportedEnvironment'); // TODO:fallback to native implementation } return [2 /*return*/]; }); }); }; exports.unwrapKey = unwrapKey; //# sourceMappingURL=aes.js.map