|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const crypto = require('crypto'); |
| 4 | + |
| 5 | +const createKeyAndIv = (passphrase) => { |
| 6 | + // this generates a 256-bit key and a 128-bit iv for aes-256-cbc |
| 7 | + // just like nodejs's deprecated/removed crypto.createCipher would |
| 8 | + const a = crypto.createHash('md5').update(passphrase).digest(); |
| 9 | + const b = crypto |
| 10 | + .createHash('md5') |
| 11 | + .update(Buffer.concat([a, Buffer.from(passphrase)])) |
| 12 | + .digest(); |
| 13 | + const c = crypto |
| 14 | + .createHash('md5') |
| 15 | + .update(Buffer.concat([b, Buffer.from(passphrase)])) |
| 16 | + .digest(); |
| 17 | + const bytes = Buffer.concat([a, b, c]); |
| 18 | + const key = bytes.subarray(0, 32); |
| 19 | + const iv = bytes.subarray(32, 48); |
| 20 | + return { key, iv }; |
| 21 | +}; |
| 22 | + |
| 23 | +const encrypt = (data, algorithm, passphrase, iv) => { |
| 24 | + let cipher; |
| 25 | + if (iv) { |
| 26 | + cipher = crypto.createCipheriv(algorithm, passphrase, iv); |
| 27 | + } else { |
| 28 | + console.warn( |
| 29 | + '[Deprecation notice] No IV provided, falling back to legacy key derivation.', |
| 30 | + ); |
| 31 | + console.warn( |
| 32 | + 'This will be removed in a future major release. You should encrypt your keys with a proper key and IV.', |
| 33 | + ); |
| 34 | + const { key, iv: generatedIv } = createKeyAndIv(passphrase); |
| 35 | + cipher = crypto.createCipheriv(algorithm, key, generatedIv); |
| 36 | + } |
| 37 | + const encrypted = cipher.update(data, 'utf8', 'hex') + cipher.final('hex'); |
| 38 | + return Buffer.from(encrypted).toString('base64'); |
| 39 | +}; |
| 40 | + |
| 41 | +const decrypt = (data, algorithm, passphrase, iv) => { |
| 42 | + data = Buffer.from(data, 'base64').toString(); |
| 43 | + let decipher; |
| 44 | + if (iv) { |
| 45 | + decipher = crypto.createDecipheriv(algorithm, passphrase, iv); |
| 46 | + } else { |
| 47 | + console.warn( |
| 48 | + '[Deprecation notice] No IV provided, falling back to legacy key derivation.', |
| 49 | + ); |
| 50 | + console.warn( |
| 51 | + 'This will be removed in a future major release. You should re-encrypt your keys with a proper key and IV.', |
| 52 | + ); |
| 53 | + const { key, iv: generatedIv } = createKeyAndIv(passphrase); |
| 54 | + decipher = crypto.createDecipheriv(algorithm, key, generatedIv); |
| 55 | + } |
| 56 | + const decrypted = decipher.update(data, 'hex', 'utf8') + decipher.final('utf8'); |
| 57 | + return decrypted; |
| 58 | +}; |
| 59 | + |
| 60 | +module.exports = { encrypt, decrypt }; |
0 commit comments