@meeco/cryppo
Version:
In-browser encryption and decryption. Clone of Ruby Cryppo
59 lines • 2.15 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.EncryptionKey = void 0;
const node_forge_1 = __importDefault(require("node-forge"));
const util_js_1 = require("./util.js");
const { random } = node_forge_1.default;
/**
* 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.
*/
class EncryptionKey {
value;
static fromSerialized(value) {
this.checkStringValue(value);
return new EncryptionKey((0, util_js_1.binaryStringToBytes)((0, util_js_1.decodeSafe64)(value)));
}
static fromBytes(bytes) {
this.checkBytesValue(bytes);
return new EncryptionKey(bytes);
}
static generateRandom(length = 32) {
return new EncryptionKey((0, util_js_1.binaryStringToBytes)(random.getBytesSync(length)));
}
static checkStringValue(value) {
value = value.trim();
if (!value) {
throw new Error('bytes are empty or undefined');
}
}
static checkBytesValue(value) {
if (!value || value.length === 0) {
throw new Error('bytes are empty or undefined');
}
}
/**
* 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.
*/
constructor(value) {
this.value = value;
}
/**
* Encode a key in a human-readable and url-safe format.
*/
get serialize() {
return (0, util_js_1.encodeSafe64)((0, util_js_1.bytesToBinaryString)(this.value));
}
get bytes() {
return this.value;
}
}
exports.EncryptionKey = EncryptionKey;
//# sourceMappingURL=encryption-key.js.map