@reshuffle/monday-redis-service
Version:
Reshuffle service for mirroring Monday to Redis
57 lines • 1.94 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
exports.__esModule = true;
exports.Cipher = void 0;
var crypto_1 = __importDefault(require("crypto"));
// Symmetric text encryption
//
var Cipher = /** @class */ (function () {
// Create a new cipher with the specified encryption key.
//
// @param key encryption key (32 bytes)
//
function Cipher(key) {
if (typeof key === 'string' && Cipher.keyRegex.test(key)) {
this.key = Buffer.from(key, 'hex');
}
else if (typeof key === 'object' &&
key instanceof Buffer &&
key.length === Cipher.KEY_LENGTH) {
this.key = key;
}
else {
throw new Error("Invalid encryption key: " + key);
}
}
// Encrypt.
//
// @param text clear text string
//
// @return encrypted string
//
Cipher.prototype.encrypt = function (text) {
var iv = crypto_1["default"].randomBytes(16);
var cipher = crypto_1["default"].createCipheriv('aes256', this.key, iv);
var ct = cipher.update(text, 'utf8', 'hex') + cipher.final('hex');
return JSON.stringify({ iv: iv, ct: ct });
};
// Decrypt.
//
// @param encoded encrypted string produced by encrypt()
//
// @return clear text string
//
Cipher.prototype.decrypt = function (encoded) {
var _a = JSON.parse(encoded), iv = _a.iv, ct = _a.ct;
var ivb = Buffer.from(iv, 'hex');
var decipher = crypto_1["default"].createDecipheriv('aes256', this.key, ivb);
return decipher.update(ct, 'hex', 'utf8') + decipher.final('utf8');
};
Cipher.KEY_LENGTH = 32;
Cipher.keyRegex = new RegExp("^[0-9a-fA-F]{" + Cipher.KEY_LENGTH * 2 + "}$");
return Cipher;
}());
exports.Cipher = Cipher;
//# sourceMappingURL=Cipher.js.map