Last active
August 23, 2024 14:42
-
-
Save Hoyasumii/9feadbe5ff0e6f0273bdf05567715a60 to your computer and use it in GitHub Desktop.
AES-128 Encrypter & Decrypter for Bun - UNSAFE
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import crypto from "crypto"; | |
export class AES128 { | |
private iv: NodeJS.ArrayBufferView; | |
private key: NodeJS.ArrayBufferView; | |
constructor(key: string, iv: string) { | |
if (key.length !== 16) { | |
throw new Error( | |
"Não foi possível construir o AES128 devido ao key que possui um comprimento diferente de 16." | |
); | |
} | |
if (iv.length !== 16) { | |
throw new Error( | |
"Não foi possível construir o AES128 devido ao iv que possui um comprimento diferente de 16." | |
); | |
} | |
this.key = Buffer.from(key, "utf-8"); | |
this.iv = Buffer.from(iv, "utf-8"); | |
} | |
public encrypt(text: string): string { | |
const cipher = crypto.createCipheriv("aes-128-cbc", this.key, this.iv); | |
return cipher.update(text, "utf-8", "hex") + cipher.final("hex"); | |
} | |
public decrypt(text: string): string { | |
const decipher = crypto.createDecipheriv("aes-128-cbc", this.key, this.iv); | |
return decipher.update(text, "hex", "utf-8") + decipher.final("utf-8"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment