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
67
78function EncryptedAttributes ( attributes , options ) {
89 options = options || { }
@@ -24,9 +25,11 @@ function EncryptedAttributes (attributes, options) {
2425 // Recommended 96-bit nonce with AES-GCM.
2526 let iv = crypto . randomBytes ( 12 )
2627 let aad = Buffer . from (
27- `aes-256-gcm $${ options . verifyId ? obj . id . toString ( ) : '' } $${ options . keyId } ` )
28+ `${ alg } $${ options . verifyId ? obj . id . toString ( ) : '' } $${ options . keyId } ` )
2829 let key = Buffer . from ( options . keys [ options . keyId ] , 'base64' )
29- let gcm = crypto . createCipheriv ( 'aes-256-gcm' , key , iv ) . setAAD ( aad )
30+ let gcm = crypto . createCipheriv ( alg , key , iv )
31+ gcm . setAAD ( aad )
32+
3033 let result = gcm . update ( val , 'utf8' , 'base64' ) + gcm . final ( 'base64' )
3134
3235 return aad . toString ( 'base64' ) + '$' +
@@ -54,16 +57,26 @@ function EncryptedAttributes (attributes, options) {
5457 if ( options . verifyId && ! obj . id ) {
5558 throw new Error ( 'Cannot decrypt without \'id\' attribute' )
5659 }
57- let [ aad , iv , payload , tag ] = val . split ( '$' ) . map ( ( x ) => Buffer . from ( x , 'base64' ) )
58- let [ , id , keyId ] = aad . toString ( ) . split ( '$' )
60+ let parts = val . split ( '$' ) . map ( ( x ) => Buffer . from ( x , 'base64' ) )
61+ let aad = parts [ 0 ]
62+ let iv = parts [ 1 ]
63+ let payload = parts [ 2 ]
64+ let tag = parts [ 3 ]
65+
66+ parts = aad . toString ( ) . split ( '$' )
67+ let id = parts [ 1 ]
68+ let keyId = parts [ 2 ]
69+
5970 if ( options . verifyId && ( id !== obj . id . toString ( ) ) ) {
6071 throw new Error ( 'Encrypted attribute has invalid id' )
6172 }
6273 if ( ! options . keys [ keyId ] ) {
6374 throw new Error ( 'Encrypted attribute has invalid key id' )
6475 }
6576 let key = Buffer . from ( options . keys [ keyId ] , 'base64' )
66- let gcm = crypto . createDecipheriv ( 'aes-256-gcm' , key , iv ) . setAAD ( aad ) . setAuthTag ( tag )
77+ let gcm = crypto . createDecipheriv ( alg , key , iv )
78+ gcm . setAAD ( aad )
79+ gcm . setAuthTag ( tag )
6780
6881 return gcm . update ( payload , 'binary' , 'utf8' ) + gcm . final ( 'utf8' )
6982 }
0 commit comments