UNPKG

@bakesaled/cement

Version:

A library that encrypts and decrypt files or strings.

436 lines (419 loc) 17.7 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var argon2 = require('argon2'); var crypto = require('crypto'); var stream = require('stream'); var fs = require('fs-extra'); var path = require('path'); var zlib = require('zlib'); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } function __awaiter(thisArg, _arguments, P, generator) { 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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(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 (_) 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 EncryptedValueModel = (function () { function EncryptedValueModel(hash, iv, tag, value) { this.hash = hash; this.iv = iv.toString('hex'); this.tag = tag.toString('hex'); this.value = value; } Object.defineProperty(EncryptedValueModel.prototype, "hashAsBuffer", { get: function () { return Buffer.from(this.hash, 'base64'); }, enumerable: true, configurable: true }); Object.defineProperty(EncryptedValueModel.prototype, "ivAsBuffer", { get: function () { return Buffer.from(this.iv, 'hex'); }, enumerable: true, configurable: true }); Object.defineProperty(EncryptedValueModel.prototype, "tagAsBuffer", { get: function () { return Buffer.from(this.tag, 'hex'); }, enumerable: true, configurable: true }); Object.defineProperty(EncryptedValueModel.prototype, "hashPart", { get: function () { return EncryptedValueModel.extractHashPart(this.hash); }, enumerable: true, configurable: true }); Object.defineProperty(EncryptedValueModel.prototype, "header", { get: function () { return ("cement" + EncryptedValueModel.separator + this.iv + ("" + EncryptedValueModel.separator + this.tag) + ("" + EncryptedValueModel.separator + this.hash) + ("" + EncryptedValueModel.separator)); }, enumerable: true, configurable: true }); EncryptedValueModel.extractHashPart = function (argon2iHash) { return argon2iHash.split(',')[2].split('$')[2]; }; EncryptedValueModel.fromString = function (source) { var sourceParts = EncryptedValueModel.validateString(source); return new EncryptedValueModel(sourceParts[3], Buffer.from(sourceParts[1], 'hex'), Buffer.from(sourceParts[2], 'hex'), sourceParts[4]); }; EncryptedValueModel.validateString = function (source) { var sourceParts = source.split('#'); if (sourceParts.length !== 5) { throw new Error('String has invalid parts.'); } if (sourceParts[0] !== 'cement') { throw new Error('String is corrupt.'); } return sourceParts; }; EncryptedValueModel.prototype.toString = function () { return "" + this.header + EncryptedValueModel.newLine + this.value; }; EncryptedValueModel.newLine = '\n'; EncryptedValueModel.separator = '#'; return EncryptedValueModel; }()); var config = { KEY_LENGTH: 32, IV_LENGTH: 12, BASE64_ENCODING: 'base64', UTF8_ENCODING: 'utf8', CIPHER_ALGORITHM: 'aes-256-gcm', UTF8_FILE_ENCODING: 'utf-8', FILE_EXTENSION: '.cmt', }; var CryptoService = (function () { function CryptoService() { } CryptoService.prototype.generateHash = function (password) { return __awaiter(this, void 0, void 0, function () { var salt, hash, e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: salt = crypto.randomBytes(config.KEY_LENGTH); _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4, argon2.hash(password, { salt: salt, type: argon2.argon2i, hashLength: config.KEY_LENGTH })]; case 2: hash = _a.sent(); return [3, 4]; case 3: e_1 = _a.sent(); console.error('error', e_1); return [3, 4]; case 4: return [2, hash]; } }); }); }; CryptoService.prototype.verifyHash = function (hash, password) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4, argon2.verify(hash, password)]; case 1: return [2, _a.sent()]; } }); }); }; CryptoService.prototype.encrypt = function (hash, value) { var _this = this; return new Promise(function (resolve, reject) { try { var encryptedValue = _this.encryptSync(hash, value); resolve(encryptedValue); } catch (e) { reject(e); } }); }; CryptoService.prototype.encryptSync = function (hash, value) { var iv = crypto.randomBytes(config.IV_LENGTH); var hashPart = EncryptedValueModel.extractHashPart(hash); var cipher = crypto.createCipheriv(config.CIPHER_ALGORITHM, Buffer.from(hashPart, config.BASE64_ENCODING), iv); var result = cipher.update(value, config.UTF8_ENCODING, config.BASE64_ENCODING); result += cipher.final(config.BASE64_ENCODING); var tag = cipher.getAuthTag(); return new EncryptedValueModel(hash, iv, tag, result); }; CryptoService.prototype.decrypt = function (hash, encryptedValue) { var _this = this; return new Promise(function (resolve, reject) { try { var result = _this.decryptSync(hash, encryptedValue); resolve(result); } catch (e) { reject(e); } }); }; CryptoService.prototype.decryptSync = function (hash, encryptedValue) { var iv = encryptedValue.ivAsBuffer; var tag = encryptedValue.tagAsBuffer; var decipher = crypto.createDecipheriv(config.CIPHER_ALGORITHM, Buffer.from(EncryptedValueModel.extractHashPart(hash), config.BASE64_ENCODING), iv); decipher.setAuthTag(tag); var result = decipher.update(encryptedValue.value, config.BASE64_ENCODING, config.UTF8_ENCODING); result += decipher.final(config.UTF8_ENCODING); return result.toString(); }; return CryptoService; }()); var DecryptTransform = (function (_super) { __extends(DecryptTransform, _super); function DecryptTransform(cryptoService, options) { var _this = _super.call(this, options) || this; _this.cryptoService = cryptoService; return _this; } DecryptTransform.prototype._transform = function (chunk, encoding, callback) { if (this.header) { this.extractBody(chunk); } else { this.prev = null; this.extractHeader(chunk); } callback(); }; DecryptTransform.prototype._flush = function (callback) { if (!this.header) { callback(new Error('Header is invalid')); } try { var encryptedValue = EncryptedValueModel.fromString(this.header); var value = this.cryptoService.decryptSync(encryptedValue.hash, encryptedValue); this.push(value); } catch (e) { callback(e); } callback(); }; DecryptTransform.prototype.extractHeader = function (chunk) { if (typeof chunk === 'string') { chunk = Buffer.from(chunk); } var buffer = chunk; var start = 0; if (this.prev) { start = this.prev.length; buffer = Buffer.concat([this.prev, chunk]); this.prev = null; } var bufferLength = buffer.length; for (var i = start; i < bufferLength; i++) { var char = buffer[i]; if (char === EncryptedValueModel.newLine.charCodeAt(0)) { this.header = buffer.toString(config.UTF8_FILE_ENCODING); } } this.prev = buffer; }; DecryptTransform.prototype.extractBody = function (chunk) { if (typeof chunk === 'string') { chunk = Buffer.from(chunk); } var buffer = chunk; if (this.prev) { buffer = Buffer.concat([this.prev, chunk]); this.prev = null; } this.prev = buffer; }; return DecryptTransform; }(stream.Transform)); var EncryptTransform = (function (_super) { __extends(EncryptTransform, _super); function EncryptTransform(cryptoService, hash, options) { var _this = _super.call(this, options) || this; _this.cryptoService = cryptoService; _this.hash = hash; return _this; } EncryptTransform.prototype._transform = function (chunk, encoding, callback) { if (typeof chunk === 'string') { chunk = Buffer.from(chunk); } var buffer = chunk; if (this.prev) { buffer = Buffer.concat([this.prev, chunk]); this.prev = null; } this.prev = buffer; callback(); }; EncryptTransform.prototype._flush = function (callback) { try { var value = this.cryptoService.encryptSync(this.hash, this.prev); this.push(value.toString()); } catch (e) { callback(e); } callback(); }; return EncryptTransform; }(stream.Transform)); var FileService = (function () { function FileService(cryptoService) { this.cryptoService = cryptoService; } FileService.prototype.create = function (password, filePath, content) { return __awaiter(this, void 0, void 0, function () { var resultStream; return __generator(this, function (_a) { switch (_a.label) { case 0: resultStream = new stream.Readable(); resultStream.push(content); resultStream.push(null); return [4, this.encryptToFile(password, filePath, resultStream)]; case 1: _a.sent(); return [2]; } }); }); }; FileService.prototype.encryptExistingFile = function (password, filePath) { return __awaiter(this, void 0, void 0, function () { var readStream; return __generator(this, function (_a) { switch (_a.label) { case 0: readStream = fs.createReadStream(filePath); return [4, this.encryptToFile(password, filePath, readStream)]; case 1: _a.sent(); return [2]; } }); }); }; FileService.prototype.decryptFile = function (password, filePath) { return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { return [2, new Promise(function (resolve, reject) { var decryptedData = ''; var readStream = fs.createReadStream(filePath); var unzip = zlib.createGunzip(); readStream .pipe(unzip) .pipe(new DecryptTransform(_this.cryptoService)) .on('data', function (data) { decryptedData += data; }) .on('error', function (e) { reject(e); }) .on('finish', function () { resolve(decryptedData); }); })]; }); }); }; FileService.prototype.encryptToFile = function (password, filePath, stream) { return __awaiter(this, void 0, void 0, function () { var hash; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4, this.cryptoService.generateHash(password)]; case 1: hash = _a.sent(); return [2, new Promise(function (resolve, reject) { var encryptTransform = new EncryptTransform(_this.cryptoService, hash); var writeStream = fs.createWriteStream(path.join(filePath + config.FILE_EXTENSION)); stream .pipe(encryptTransform) .pipe(zlib.createGzip()) .pipe(writeStream) .on('error', function (e) { return reject(e); }) .on('finish', function () { resolve(); }); })]; } }); }); }; return FileService; }()); exports.CryptoService = CryptoService; exports.DecryptTransform = DecryptTransform; exports.EncryptTransform = EncryptTransform; exports.EncryptedValueModel = EncryptedValueModel; exports.FileService = FileService; exports.config = config; //# sourceMappingURL=main.js.map