js-crypto-aes
Version:
Universal Module for AES Encryption and Decryption in JavaScript
246 lines • 11.9 kB
JavaScript
;
/**
* webapi.js
*/
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 };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.decrypt = exports.encrypt = exports.unwrapKey = exports.wrapKey = void 0;
/**
* WebCrypto KeyWrapping function simply uses encrypt function.
* @param keyToBeWrapped {Uint8Array} - plaintext key
* @param wrappingKey {Uint8Array} - wrapping key
* @param name {string} - 'AES-KW'
* @param iv {Uint8Array} - default is '0xA6A6A6A6A6A6A6A6'
* @param webCrypto {Object} - crypto.subtle object
* @return {Uint8Array} - Unwrapped Key
*/
var wrapKey = function (keyToBeWrapped, wrappingKey, _a, webCrypto) {
var name = _a.name, iv = _a.iv;
return __awaiter(void 0, void 0, void 0, function () {
var kek, cek, data, e_1;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_b.trys.push([0, 4, , 5]);
return [4 /*yield*/, webCrypto.importKey('raw', wrappingKey, { name: name }, false, ['wrapKey', 'unwrapKey'])];
case 1:
kek = _b.sent();
return [4 /*yield*/, webCrypto.importKey('raw', keyToBeWrapped, { name: name }, true, ['wrapKey', 'unwrapKey'])];
case 2:
cek = _b.sent();
return [4 /*yield*/, webCrypto.wrapKey('raw', cek, kek, { name: name, iv: iv })];
case 3:
data = _b.sent();
return [2 /*return*/, new Uint8Array(data)];
case 4:
e_1 = _b.sent();
if (e_1 instanceof Error) {
throw new Error("WebCrypto_FailedToWrapKey - ".concat(e_1.message));
}
else {
throw new Error('WebCrypto_FailedToWrapKey');
}
return [3 /*break*/, 5];
case 5: return [2 /*return*/];
}
});
});
};
exports.wrapKey = wrapKey;
/**
* WebCrypto KeyUnwrapping function as well as keyWrapping
* @param wrappedKey {Uint8Array} - Wrapped key
* @param unwrappingKey {Uint8Array} - Key used for wrapping
* @param name {string} - 'AES-KW'
* @param iv {Uint8Array} - default is '0xA6A6A6A6A6A6A6A6'
* @param webCrypto {Object} - crypto.subtle object
* @return {Uint8Array} - Unwrapped Key
*/
var unwrapKey = function (wrappedKey, unwrappingKey, _a, webCrypto) {
var name = _a.name, iv = _a.iv;
return __awaiter(void 0, void 0, void 0, function () {
var kek, cek, _b, e_2;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
_c.trys.push([0, 4, , 5]);
return [4 /*yield*/, webCrypto.importKey('raw', unwrappingKey, { name: name }, false, ['wrapKey', 'unwrapKey'])];
case 1:
kek = _c.sent();
return [4 /*yield*/, webCrypto.unwrapKey('raw', wrappedKey, kek, { name: name, iv: iv }, { name: 'AES-GCM' }, true, ['encrypt', 'decrypt'])];
case 2:
cek = _c.sent();
_b = Uint8Array.bind;
return [4 /*yield*/, webCrypto.exportKey('raw', cek)];
case 3: return [2 /*return*/, new (_b.apply(Uint8Array, [void 0, _c.sent()]))()];
case 4:
e_2 = _c.sent();
if (e_2 instanceof Error) {
throw new Error("WebCrypto_FailedToUnwrapKey - ".concat(e_2.message));
}
else {
throw new Error('WebCrypto_FailedToUnwrapKey');
}
return [3 /*break*/, 5];
case 5: return [2 /*return*/];
}
});
});
};
exports.unwrapKey = unwrapKey;
/**
* Encrypt data through AES of WebCrypto API.
* @param {Uint8Array} msg - Plaintext message to be encrypted.
* @param {Uint8Array} key - Byte array of symmetric key.
* @param {String} name - Name of AES algorithm like 'AES-GCM'.
* @param {Uint8Array} [iv] - Byte array of initial vector if required.
* @param {Uint8Array} [additionalData] - Byte array of additional data if required.
* @param {Number} [tagLength] - Authentication tag length if required.
* @param {Object} webCrypto - WebCrypto object, i.e., window.crypto.subtle
* @return {Promise<Uint8Array>} - Encrypted data byte array.
* @throws {Error} - Throws if UnsupportedCipher.
*/
var encrypt = function (msg, key, _a, webCrypto) {
var _b = _a.name, name = _b === void 0 ? 'AES-GCM' : _b, iv = _a.iv, additionalData = _a.additionalData, tagLength = _a.tagLength;
return __awaiter(void 0, void 0, void 0, function () {
var encryptionConfig, sessionKeyObj, data, e_3;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
encryptionConfig = setCipherParams({ name: name, iv: iv, additionalData: additionalData, tagLength: tagLength });
_c.label = 1;
case 1:
_c.trys.push([1, 4, , 5]);
return [4 /*yield*/, webCrypto.importKey('raw', key, encryptionConfig, false, ['encrypt', 'decrypt'])];
case 2:
sessionKeyObj = _c.sent();
return [4 /*yield*/, webCrypto.encrypt(encryptionConfig, sessionKeyObj, msg)];
case 3:
data = _c.sent();
return [2 /*return*/, new Uint8Array(data)];
case 4:
e_3 = _c.sent();
if (e_3 instanceof Error) {
throw new Error("WebCrypto_EncryptionFailure: ".concat(e_3.message));
}
else {
throw new Error('WebCrypto_EncryptionFailure');
}
return [3 /*break*/, 5];
case 5: return [2 /*return*/];
}
});
});
};
exports.encrypt = encrypt;
/**
* Decrypt data through AES of WebCrypto API.
* @param {Uint8Array} data - Encrypted message to be decrypted.
* @param {Uint8Array} key - Byte array of symmetric key.
* @param {String} name - Name of AES algorithm like 'AES-GCM'.
* @param {Uint8Array} [iv] - Byte array of initial vector if required.
* @param {Uint8Array} [additionalData] - Byte array of additional data if required.
* @param {Number} [tagLength] - Authentication tag length if required.
* @param {Object} webCrypto - WebCrypto object, i.e., window.crypto.subtle
* @return {Promise<Uint8Array>} - Decrypted plaintext message.
* @throws {Error} - Throws if UnsupportedCipher or DecryptionFailure.
*/
var decrypt = function (data, key, _a, webCrypto) {
var name = _a.name, iv = _a.iv, additionalData = _a.additionalData, tagLength = _a.tagLength;
return __awaiter(void 0, void 0, void 0, function () {
var decryptionConfig, sessionKeyObj, msg, e_4;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
decryptionConfig = setCipherParams({ name: name, iv: iv, additionalData: additionalData, tagLength: tagLength });
_b.label = 1;
case 1:
_b.trys.push([1, 4, , 5]);
return [4 /*yield*/, webCrypto.importKey('raw', key, decryptionConfig, false, ['encrypt', 'decrypt'])];
case 2:
sessionKeyObj = _b.sent();
return [4 /*yield*/, webCrypto.decrypt(decryptionConfig, sessionKeyObj, data)];
case 3:
msg = _b.sent();
return [2 /*return*/, new Uint8Array(msg)];
case 4:
e_4 = _b.sent();
if (e_4 instanceof Error) {
throw new Error("WebCrypto_DecryptionFailure: ".concat(e_4.message));
}
else {
throw new Error('WebCrypto_DecryptionFailure');
}
return [3 /*break*/, 5];
case 5: return [2 /*return*/];
}
});
});
};
exports.decrypt = decrypt;
/**
* Set params for encryption algorithms.
* @param {String} name - Name of AES algorithm like 'AES-GCM'.
* @param {Uint8Array} [iv] - Byte array of initial vector if required.
* @param {Uint8Array} [additionalData] - Byte array of additional data if required.
* @param {Number} [tagLength] - Authentication tag length if required.
*/
var setCipherParams = function (_a) {
var name = _a.name, iv = _a.iv, additionalData = _a.additionalData, tagLength = _a.tagLength;
var alg = { name: name, iv: iv, additionalData: additionalData, tagLength: tagLength };
switch (name) {
case 'AES-GCM': {
alg.tagLength = tagLength * 8;
break;
}
case 'AES-CBC': {
break;
}
case 'AES-CTR': {
if (iv.length === 0 || iv.length > 16)
throw new Error('InvalidIVLength');
alg.counter = new Uint8Array(16);
alg.counter.set(iv);
alg.counter[15] += 1;
alg.length = 128; // todo: this might be (16 - iv.length) * 8.
break;
}
}
return alg;
};
//# sourceMappingURL=webapi.js.map