UNPKG

@meeco/cryppo

Version:

In-browser encryption and decryption. Clone of Ruby Cryppo

64 lines (63 loc) 2.37 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.EncryptionKey = void 0; var node_forge_1 = require("node-forge"); var util_1 = require("./util"); /** * SymmetricKey that can be used to encrypt and decrypt data * This wrapper ensures that keys can be safely serialized as JSON (by encoding them as URL-Safe Base64) * and avoids confusion when dealing with converting to and from this encoded format. */ var EncryptionKey = /** @class */ (function () { /** * The constructor is intentionally private as we want the user ot be explicit as to whether the value coming * in is raw bytes or a base64 encoded version. * * @param value Value as binary string. Avoid outputting to console but should be used for actual encryption. */ function EncryptionKey(value) { this.value = value; } EncryptionKey.fromSerialized = function (value) { this.checkStringValue(value); return new EncryptionKey(util_1.binaryStringToBytes(util_1.decodeSafe64(value))); }; EncryptionKey.fromBytes = function (bytes) { this.checkBytesValue(bytes); return new EncryptionKey(bytes); }; EncryptionKey.generateRandom = function (length) { if (length === void 0) { length = 32; } return new EncryptionKey(util_1.binaryStringToBytes(node_forge_1.random.getBytesSync(length))); }; EncryptionKey.checkStringValue = function (value) { value = value.trim(); if (!value) { throw new Error('bytes are empty or undefined'); } }; EncryptionKey.checkBytesValue = function (value) { if (!value || value.length === 0) { throw new Error('bytes are empty or undefined'); } }; Object.defineProperty(EncryptionKey.prototype, "serialize", { /** * Encode a key in a human-readable and url-safe format. */ get: function () { return util_1.encodeSafe64(util_1.bytesToBinaryString(this.value)); }, enumerable: false, configurable: true }); Object.defineProperty(EncryptionKey.prototype, "bytes", { get: function () { return this.value; }, enumerable: false, configurable: true }); return EncryptionKey; }()); exports.EncryptionKey = EncryptionKey;