Skip to content

Instantly share code, notes, and snippets.

@raynirola
Last active July 20, 2023 05:37
Show Gist options
  • Save raynirola/f73d77587cde043b5eff4d006ad41152 to your computer and use it in GitHub Desktop.
Save raynirola/f73d77587cde043b5eff4d006ad41152 to your computer and use it in GitHub Desktop.
import { createCipheriv, createDecipheriv, randomBytes, createHash } from 'node:crypto';
type Preprocessor = (input: string) => string;
type Transformer = (input: string) => string;
class EncryptionError extends Error {
constructor(message: string) {
super(message);
this.name = 'EncryptionError';
}
}
class Encryption {
private key: Buffer;
private iv: Buffer;
constructor(private secret: string) {
if (!secret) throw new EncryptionError('Encryption secret not provided.');
this.key = this.generateKey();
this.iv = this.generateIV();
}
private generateIV(): Buffer {
const hash = createHash('sha256');
hash.update(this.key);
return hash.digest().slice(0, 16);
}
private generateKey(): Buffer {
const hash = createHash('sha256');
hash.update(this.secret);
return hash.digest();
}
public encrypt(text: string, preprocessors: Preprocessor[] = []): string {
const processedText = preprocessors.reduce((result, preprocessor) => preprocessor(result), text);
const cipher = createCipheriv('aes-256-cbc', this.key, this.iv);
let encrypted = cipher.update(processedText, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}
public decrypt(encryptedText: string, transformers: Transformer[] = []): string {
const decipher = createDecipheriv('aes-256-cbc', this.key, this.iv);
let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return transformers.reduceRight((result, transformer) => transformer(result), decrypted);
}
}
export default Encryption;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment