UNPKG

@meeco/cryppo

Version:

In-browser encryption and decryption. Clone of Ruby Cryppo

52 lines 1.8 kB
import forge from 'node-forge'; import { binaryStringToBytes, bytesToBinaryString, decodeSafe64, encodeSafe64 } from './util.js'; const { random } = forge; /** * 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. */ export class EncryptionKey { value; static fromSerialized(value) { this.checkStringValue(value); return new EncryptionKey(binaryStringToBytes(decodeSafe64(value))); } static fromBytes(bytes) { this.checkBytesValue(bytes); return new EncryptionKey(bytes); } static generateRandom(length = 32) { return new EncryptionKey(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 encodeSafe64(bytesToBinaryString(this.value)); } get bytes() { return this.value; } } //# sourceMappingURL=encryption-key.js.map