JSFiddle - React, Tailwind, and code Playground

by henser

TypeScript

class Encryption {
    private key: string;
    private iv: string;

    private static ENCRYPTION_METHOD = 'aes-256-cbc';
    private static HASH_ALGORITHM = 'sha512';
    private static HEX_ENCODING = 'hex';
    private static UTF8_ENCODING = 'utf8';

    constructor() {
        this.key = crypto.generateRandomBytes(32);
        this.iv = crypto.generateRandomBytes(16);
        console.log(key);
        console.log(iv);
    }

    encrypt(secret: string): string {
        const cipher: Cipher = crypto.createCipheriv(
            Encryption.ENCRYPTION_METHOD as CipherCCMTypes,
            this.key as CipherKey,
            this.iv as BinaryLike,
        );

        return (
            cipher.update(secret, Encryption.UTF8_ENCODING as Encoding, Encryption.HEX_ENCODING as Encoding) +
            cipher.final(Encryption.HEX_ENCODING as BufferEncoding)
        );
    }

    decrypt(encryptedSecret: string): string {
        const decipher: Cipher = crypto.createDecipheriv(
            Encryption.ENCRYPTION_METHOD as string,
            this.key as CipherKey,
            this.iv as BinaryLike,
        );
        return (
            decipher.update(
                encryptedSecret,
                Encryption.HEX_ENCODING as Encoding,
                Encryption.UTF8_ENCODING as Encoding,
            ) + decipher.final(Encryption.UTF8_ENCODING as BufferEncoding)
        );
    }
}


let enc = new Encryption();
console.log(enc.encrypt('test'));