Created
December 14, 2020 08:00
-
-
Save meirkl/85f6e8556376e2929521600a038e04bf to your computer and use it in GitHub Desktop.
AES 256 GCM Typescript
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 * as crypto from 'crypto'; | |
const ALGORITHM = 'aes-256-gcm'; | |
const IV_LENGTH = 16; | |
const SALT_LENGTH = 64; | |
const TAG_LENGTH = 16; | |
const TAG_POSITION = SALT_LENGTH + IV_LENGTH; | |
const ENCRYPTED_POSITION = TAG_POSITION + TAG_LENGTH; | |
export class AES { | |
constructor(private secret: string) {} | |
getKey(salt: Buffer) { | |
return crypto.pbkdf2Sync(this.secret, salt, 100000, 32, 'sha512'); | |
} | |
encrypt(plainText: string) { | |
const iv = crypto.randomBytes(IV_LENGTH); | |
const salt = crypto.randomBytes(SALT_LENGTH); | |
const key = this.getKey(salt); | |
const cipher = crypto.createCipheriv(ALGORITHM, key, iv); | |
const encrypted = Buffer.concat([ | |
cipher.update(String(plainText), 'utf8'), | |
cipher.final(), | |
]); | |
const tag = cipher.getAuthTag(); | |
return Buffer.concat([salt, iv, tag, encrypted]).toString('base64'); | |
} | |
decrypt(cipherText: string) { | |
const stringValue = Buffer.from(String(cipherText), 'base64'); | |
const salt = stringValue.slice(0, SALT_LENGTH); | |
const iv = stringValue.slice(SALT_LENGTH, TAG_POSITION); | |
const tag = stringValue.slice(TAG_POSITION, ENCRYPTED_POSITION); | |
const encrypted = stringValue.slice(ENCRYPTED_POSITION); | |
const key = this.getKey(salt); | |
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv); | |
decipher.setAuthTag(tag); | |
return decipher.update(encrypted) + decipher.final('utf8'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment