|
| 1 | +const crypto = require('crypto'); |
| 2 | + |
| 3 | +const CIPHER_ALGORITHM = 'aes-256-gcm'; |
| 4 | +const IV_LENGTH = 16; |
| 5 | +const TAG_LENGTH = 16; |
| 6 | +const SALT_LENGTH = 64; |
| 7 | +const ITERATIONS = 10000; |
| 8 | + |
| 9 | +const tagPosition = SALT_LENGTH + IV_LENGTH; |
| 10 | +const encryptedPosition = tagPosition + TAG_LENGTH; |
| 11 | + |
| 12 | +const getKey = (salt, secret) => { |
| 13 | + return crypto.pbkdf2Sync(secret, salt, ITERATIONS, 32, 'sha256'); |
| 14 | +}; |
| 15 | + |
| 16 | +const gcm = { |
| 17 | + encrypt: (input, secret) => { |
| 18 | + const iv = crypto.randomBytes(IV_LENGTH); |
| 19 | + const salt = crypto.randomBytes(SALT_LENGTH); |
| 20 | + |
| 21 | + const AES_KEY = getKey(salt, secret); |
| 22 | + |
| 23 | + const cipher = crypto.createCipheriv(CIPHER_ALGORITHM, AES_KEY, iv); |
| 24 | + const encrypted = Buffer.concat([cipher.update(String(input), 'utf8'), cipher.final()]); |
| 25 | + |
| 26 | + const tag = cipher.getAuthTag(); |
| 27 | + |
| 28 | + return Buffer.concat([salt, iv, tag, encrypted]).toString('hex'); |
| 29 | + }, |
| 30 | + |
| 31 | + decrypt: (input, secret) => { |
| 32 | + const inputValue = Buffer.from(String(input), 'hex'); |
| 33 | + const salt = inputValue.subarray(0, SALT_LENGTH); |
| 34 | + const iv = inputValue.subarray(SALT_LENGTH, tagPosition); |
| 35 | + const tag = inputValue.subarray(tagPosition, encryptedPosition); |
| 36 | + const encrypted = inputValue.subarray(encryptedPosition); |
| 37 | + |
| 38 | + const key = getKey(salt, secret); |
| 39 | + |
| 40 | + const decipher = crypto.createDecipheriv(CIPHER_ALGORITHM, key, iv); |
| 41 | + |
| 42 | + decipher.setAuthTag(tag); |
| 43 | + |
| 44 | + return decipher.update(encrypted) + decipher.final('utf8'); |
| 45 | + }, |
| 46 | +}; |
| 47 | + |
| 48 | +// Usage: `node scripts/backend/descrypt_email.js` |
| 49 | +// Uncomment below to use a gcm function |
| 50 | +// console.log( |
| 51 | +// 'Decrypt email', |
| 52 | +// gcm.decrypt( |
| 53 | +// '', // |
| 54 | +// process.env.AES_ENCRYPTION_SECRET |
| 55 | +// ) |
| 56 | +// ); |
0 commit comments