11const crypto = require ( 'crypto' ) ;
22
3- const encryptionType = 'aes-256-cbc' ;
4-
53function generateIv ( ) {
6- return crypto . randomBytes ( 16 ) ;
4+ return crypto . randomBytes ( 32 ) ;
75}
86
7+ const algorithm = 'AES-256-GCM' ;
8+
99/**
1010 * Encrypt a secret
1111 * @param {String } data Data to encrypt
@@ -18,14 +18,18 @@ function encrypt(data, encryptionKey) {
1818 const iv = generateIv ( ) ;
1919
2020 // Cipher
21- const cipher = crypto . createCipheriv ( encryptionType , Buffer . from ( encryptionKey ) , iv ) ;
21+ const cipher = crypto . createCipheriv ( algorithm , encryptionKey , iv ) ;
2222
2323 // Encrypt the data
24- let encryptedSecret = cipher . update ( data ) ;
25- encryptedSecret = Buffer . concat ( [ encryptedSecret , cipher . final ( ) ] ) ;
24+ const encryptedData = Buffer . concat ( [
25+ cipher . update ( Buffer . from ( data , 'utf-8' ) ) ,
26+ cipher . final ( ) ,
27+ ] ) ;
28+
29+ const authTag = cipher . getAuthTag ( ) ;
2630
2731 // Embedded IV with the encrypted secret
28- return `${ iv . toString ( 'hex' ) } :${ encryptedSecret . toString ( 'hex' ) } ` ;
32+ return `${ iv . toString ( 'hex' ) } :${ authTag . toString ( 'hex' ) } : ${ encryptedData . toString ( 'hex' ) } ` ;
2933}
3034
3135/**
@@ -39,18 +43,22 @@ function decrypt(data, encryptionKey) {
3943 // Retrieve the IV from the encrypted data
4044 const encryptedData = data . split ( ':' ) ;
4145 const iv = Buffer . from ( encryptedData . shift ( ) , 'hex' ) ;
46+ const authTag = Buffer . from ( encryptedData . shift ( ) , 'hex' ) ;
4247
4348 // Retrieve the secret
4449 const encryptedSecret = Buffer . from ( encryptedData . join ( ':' ) , 'hex' ) ;
4550
4651 // Decipher
47- const decipher = crypto . createDecipheriv ( encryptionType , Buffer . from ( encryptionKey ) , iv ) ;
52+ const decipher = crypto . createDecipheriv ( algorithm , Buffer . from ( encryptionKey ) , iv ) ;
53+ decipher . setAuthTag ( authTag ) ;
4854
4955 // Decrypt the data
50- let secret = decipher . update ( encryptedSecret ) ;
51- secret = Buffer . concat ( [ secret , decipher . final ( ) ] ) ;
56+ const decrypted = Buffer . concat ( [
57+ decipher . update ( encryptedSecret ) ,
58+ decipher . final ( ) ,
59+ ] ) ;
5260
53- return secret ;
61+ return decrypted . toString ( 'utf-8' ) ;
5462}
5563
5664module . exports = { encrypt, decrypt } ;
0 commit comments