Last active
February 10, 2022 19:22
-
-
Save afraz-khan/d66be0eaecd1db58751e7324434e69c0 to your computer and use it in GitHub Desktop.
Nodejs AES Text Encrypter/Decrypter.
This file contains hidden or 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 {scryptSync, randomBytes, createCipheriv, createDecipheriv} from 'crypto'; | |
export class Encrypter { | |
private algorithm: string = 'aes-192-cbc'; | |
// encryption key for the cipher | |
private key: string; | |
constructor(key: string) { | |
this.key = key; | |
} | |
encrypt(text: string): string { | |
/* | |
* Creating a sub-internal encryption key for a particular text to be encrypted. | |
* That sub-internal encrypted key is protected by the original system | |
* "encryption-key" and a unique "salt". | |
*/ | |
const buffer = scryptSync(this.key, 'salt', 24); | |
/* | |
* Initialization Vector as the initial state for the AES algorithm. | |
* Used for randomization or for non-repeating behaviour. | |
*/ | |
const iv = randomBytes(16); | |
const cipher = createCipheriv(this.algorithm, buffer, iv); | |
const encrypted = cipher.update(text, 'utf8', 'hex'); | |
return [encrypted + cipher.final('hex'), Buffer.from(iv).toString('hex')].join('|'); | |
} | |
decrypt(encryptedText: string): string { | |
const [encrypted, iv] = encryptedText.split('|'); | |
if (!iv) { | |
throw new Error('IV not found'); | |
} | |
const buffer = scryptSync(this.key, 'salt', 24); | |
const decipher = createDecipheriv(this.algorithm, buffer, Buffer.from(iv, 'hex')); | |
const decrypted = decipher.update(encrypted, 'hex', 'utf8'); | |
return decrypted + decipher.final('utf8'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment