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