11'use strict'
22
3+ const alg = 'aes-256-gcm'
34const crypto = require ( 'crypto' )
4- const gcm = require ( 'node-aes-gcm' )
55const { get, set } = require ( 'lodash' )
66
77function EncryptedAttributes ( attributes , options ) {
88 options = options || { }
99
10+ let prefix = Buffer . from ( `${ alg } $` ) . toString ( 'base64' )
11+
1012 function encryptAttribute ( obj , val ) {
1113 // Encrypted attributes are prefixed with "aes-256-gcm$", the base64
12- // encoding of which is "YWVzLTI1Ni1nY20k" . Nulls are not encrypted.
13- if ( val == null || ( typeof val === 'string' && val . startsWith ( 'YWVzLTI1Ni1nY20k' ) ) ) {
14+ // encoding of which is in `prefix` . Nulls are not encrypted.
15+ if ( val == null || ( typeof val === 'string' && val . startsWith ( prefix ) ) ) {
1416 return val
1517 }
1618 if ( typeof val !== 'string' ) {
@@ -24,11 +26,13 @@ function EncryptedAttributes (attributes, options) {
2426 let aad = Buffer . from (
2527 `aes-256-gcm$${ options . verifyId ? obj . id . toString ( ) : '' } $${ options . keyId } ` )
2628 let key = Buffer . from ( options . keys [ options . keyId ] , 'base64' )
27- let result = gcm . encrypt ( key , iv , Buffer . from ( val ) , aad )
29+ let gcm = crypto . createCipheriv ( 'aes-256-gcm' , key , iv ) . setAAD ( aad )
30+ let result = gcm . update ( val , 'utf8' , 'base64' ) + gcm . final ( 'base64' )
31+
2832 return aad . toString ( 'base64' ) + '$' +
2933 iv . toString ( 'base64' ) + '$' +
30- result . ciphertext . toString ( 'base64' ) + '$' +
31- result . auth_tag . toString ( 'base64' ) . slice ( 0 , 22 )
34+ result + '$' +
35+ gcm . getAuthTag ( ) . toString ( 'base64' ) . slice ( 0 , 22 )
3236 }
3337
3438 function encryptAll ( obj ) {
@@ -43,8 +47,8 @@ function EncryptedAttributes (attributes, options) {
4347
4448 function decryptAttribute ( obj , val ) {
4549 // Encrypted attributes are prefixed with "aes-256-gcm$", the base64
46- // encoding of which is "YWVzLTI1Ni1nY20k" . Nulls are not encrypted.
47- if ( typeof val !== 'string' || ! val . startsWith ( 'YWVzLTI1Ni1nY20k' ) ) {
50+ // encoding of which is in `prefix` . Nulls are not encrypted.
51+ if ( typeof val !== 'string' || ! val . startsWith ( prefix ) ) {
4852 return val
4953 }
5054 if ( options . verifyId && ! obj . id ) {
@@ -59,11 +63,9 @@ function EncryptedAttributes (attributes, options) {
5963 throw new Error ( 'Encrypted attribute has invalid key id' )
6064 }
6165 let key = Buffer . from ( options . keys [ keyId ] , 'base64' )
62- let result = gcm . decrypt ( key , iv , payload , aad , tag )
63- if ( ! result . auth_ok ) {
64- throw new Error ( 'Encrypted attribute has invalid auth tag' )
65- }
66- return result . plaintext . toString ( )
66+ let gcm = crypto . createDecipheriv ( 'aes-256-gcm' , key , iv ) . setAAD ( aad ) . setAuthTag ( tag )
67+
68+ return gcm . update ( payload , 'binary' , 'utf8' ) + gcm . final ( 'utf8' )
6769 }
6870
6971 function decryptAll ( obj ) {
0 commit comments