22
33const alg = 'aes-256-gcm'
44const crypto = require ( 'crypto' )
5- const { get, set } = require ( 'lodash' )
5+ const get = require ( 'lodash' ) . get
6+ const set = require ( 'lodash' ) . set
7+ const Buffer = require ( 'safe-buffer' ) . Buffer
68
79function EncryptedAttributes ( attributes , options ) {
810 options = options || { }
@@ -24,9 +26,11 @@ function EncryptedAttributes (attributes, options) {
2426 // Recommended 96-bit nonce with AES-GCM.
2527 let iv = crypto . randomBytes ( 12 )
2628 let aad = Buffer . from (
27- `aes-256-gcm $${ options . verifyId ? obj . id . toString ( ) : '' } $${ options . keyId } ` )
29+ `${ alg } $${ options . verifyId ? obj . id . toString ( ) : '' } $${ options . keyId } ` )
2830 let key = Buffer . from ( options . keys [ options . keyId ] , 'base64' )
29- let gcm = crypto . createCipheriv ( 'aes-256-gcm' , key , iv ) . setAAD ( aad )
31+ let gcm = crypto . createCipheriv ( alg , key , iv )
32+ gcm . setAAD ( aad )
33+
3034 let result = gcm . update ( val , 'utf8' , 'base64' ) + gcm . final ( 'base64' )
3135
3236 return aad . toString ( 'base64' ) + '$' +
@@ -54,16 +58,26 @@ function EncryptedAttributes (attributes, options) {
5458 if ( options . verifyId && ! obj . id ) {
5559 throw new Error ( 'Cannot decrypt without \'id\' attribute' )
5660 }
57- let [ aad , iv , payload , tag ] = val . split ( '$' ) . map ( ( x ) => Buffer . from ( x , 'base64' ) )
58- let [ , id , keyId ] = aad . toString ( ) . split ( '$' )
61+ let parts = val . split ( '$' ) . map ( ( x ) => Buffer . from ( x , 'base64' ) )
62+ let aad = parts [ 0 ]
63+ let iv = parts [ 1 ]
64+ let payload = parts [ 2 ]
65+ let tag = parts [ 3 ]
66+
67+ parts = aad . toString ( ) . split ( '$' )
68+ let id = parts [ 1 ]
69+ let keyId = parts [ 2 ]
70+
5971 if ( options . verifyId && ( id !== obj . id . toString ( ) ) ) {
6072 throw new Error ( 'Encrypted attribute has invalid id' )
6173 }
6274 if ( ! options . keys [ keyId ] ) {
6375 throw new Error ( 'Encrypted attribute has invalid key id' )
6476 }
6577 let key = Buffer . from ( options . keys [ keyId ] , 'base64' )
66- let gcm = crypto . createDecipheriv ( 'aes-256-gcm' , key , iv ) . setAAD ( aad ) . setAuthTag ( tag )
78+ let gcm = crypto . createDecipheriv ( alg , key , iv )
79+ gcm . setAAD ( aad )
80+ gcm . setAuthTag ( tag )
6781
6882 return gcm . update ( payload , 'binary' , 'utf8' ) + gcm . final ( 'utf8' )
6983 }
0 commit comments