UNPKG

blockstack

Version:

The Blockstack Javascript library for authentication, identity, and storage.

90 lines 3.61 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const cryptoUtils_1 = require("./cryptoUtils"); class NodeCryptoAesCipher { constructor(createCipher, createDecipher) { this.createCipher = createCipher; this.createDecipher = createDecipher; } encrypt(algorithm, key, iv, data) { return tslib_1.__awaiter(this, void 0, void 0, function* () { if (algorithm !== 'aes-128-cbc' && algorithm !== 'aes-256-cbc') { throw new Error(`Unsupported cipher algorithm "${algorithm}"`); } const cipher = this.createCipher(algorithm, key, iv); const result = Buffer.concat([cipher.update(data), cipher.final()]); return Promise.resolve(result); }); } decrypt(algorithm, key, iv, data) { return tslib_1.__awaiter(this, void 0, void 0, function* () { if (algorithm !== 'aes-128-cbc' && algorithm !== 'aes-256-cbc') { throw new Error(`Unsupported cipher algorithm "${algorithm}"`); } const cipher = this.createDecipher(algorithm, key, iv); const result = Buffer.concat([cipher.update(data), cipher.final()]); return Promise.resolve(result); }); } } exports.NodeCryptoAesCipher = NodeCryptoAesCipher; class WebCryptoAesCipher { constructor(subtleCrypto) { this.subtleCrypto = subtleCrypto; } encrypt(algorithm, key, iv, data) { return tslib_1.__awaiter(this, void 0, void 0, function* () { let algo; let length; if (algorithm === 'aes-128-cbc') { algo = 'AES-CBC'; length = 128; } else if (algorithm === 'aes-256-cbc') { algo = 'AES-CBC'; length = 256; } else { throw new Error(`Unsupported cipher algorithm "${algorithm}"`); } const cryptoKey = yield this.subtleCrypto.importKey('raw', key, { name: algo, length }, false, ['encrypt']); const result = yield this.subtleCrypto.encrypt({ name: algo, iv }, cryptoKey, data); return Buffer.from(result); }); } decrypt(algorithm, key, iv, data) { return tslib_1.__awaiter(this, void 0, void 0, function* () { let algo; let length; if (algorithm === 'aes-128-cbc') { algo = 'AES-CBC'; length = 128; } else if (algorithm === 'aes-256-cbc') { algo = 'AES-CBC'; length = 256; } else { throw new Error(`Unsupported cipher algorithm "${algorithm}"`); } const cryptoKey = yield this.subtleCrypto.importKey('raw', key, { name: algo, length }, false, ['decrypt']); const result = yield this.subtleCrypto.decrypt({ name: algo, iv }, cryptoKey, data); return Buffer.from(result); }); } } exports.WebCryptoAesCipher = WebCryptoAesCipher; function createCipher() { return tslib_1.__awaiter(this, void 0, void 0, function* () { const cryptoLib = yield cryptoUtils_1.getCryptoLib(); if (cryptoLib.name === 'subtleCrypto') { return new WebCryptoAesCipher(cryptoLib.lib); } else { return new NodeCryptoAesCipher(cryptoLib.lib.createCipheriv, cryptoLib.lib.createDecipheriv); } }); } exports.createCipher = createCipher; //# sourceMappingURL=aesCipher.js.map