2
2
3
3
const alg = 'aes-256-gcm'
4
4
const crypto = require ( 'crypto' )
5
- const { get, set } = require ( 'lodash' )
5
+ const get = require ( 'lodash' ) . get
6
+ const set = require ( 'lodash' ) . set
6
7
7
8
function EncryptedAttributes ( attributes , options ) {
8
9
options = options || { }
@@ -24,9 +25,11 @@ function EncryptedAttributes (attributes, options) {
24
25
// Recommended 96-bit nonce with AES-GCM.
25
26
let iv = crypto . randomBytes ( 12 )
26
27
let aad = Buffer . from (
27
- `aes-256-gcm $${ options . verifyId ? obj . id . toString ( ) : '' } $${ options . keyId } ` )
28
+ `${ alg } $${ options . verifyId ? obj . id . toString ( ) : '' } $${ options . keyId } ` )
28
29
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
+
30
33
let result = gcm . update ( val , 'utf8' , 'base64' ) + gcm . final ( 'base64' )
31
34
32
35
return aad . toString ( 'base64' ) + '$' +
@@ -54,16 +57,26 @@ function EncryptedAttributes (attributes, options) {
54
57
if ( options . verifyId && ! obj . id ) {
55
58
throw new Error ( 'Cannot decrypt without \'id\' attribute' )
56
59
}
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
+
59
70
if ( options . verifyId && ( id !== obj . id . toString ( ) ) ) {
60
71
throw new Error ( 'Encrypted attribute has invalid id' )
61
72
}
62
73
if ( ! options . keys [ keyId ] ) {
63
74
throw new Error ( 'Encrypted attribute has invalid key id' )
64
75
}
65
76
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 )
67
80
68
81
return gcm . update ( payload , 'binary' , 'utf8' ) + gcm . final ( 'utf8' )
69
82
}
0 commit comments