-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathmongoose-field-encryption.js
238 lines (197 loc) · 7.1 KB
/
mongoose-field-encryption.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
"use strict";
const crypto = require("crypto");
const algorithm = "aes-256-cbc";
const deprecatedAlgorithm = "aes-256-ctr";
const encryptedFieldNamePrefix = "__enc_";
const encryptedFieldDataSuffix = "_d";
const encryptAes256Ctr = function(text, secret) {
const cipher = crypto.createCipher(deprecatedAlgorithm, secret);
let crypted = cipher.update(text, "utf8", "hex");
crypted += cipher.final("hex");
return crypted;
};
const decryptAes256Ctr = function(encryptedHex, secret) {
const decipher = crypto.createDecipher(deprecatedAlgorithm, secret);
let dec = decipher.update(encryptedHex, "hex", "utf8");
dec += decipher.final("utf8");
return dec;
};
const encrypt = function(clearText, secret) {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(algorithm, secret, iv);
const encrypted = cipher.update(clearText);
const finalBuffer = Buffer.concat([encrypted, cipher.final()]);
const encryptedHex = iv.toString("hex") + ":" + finalBuffer.toString("hex");
return encryptedHex;
};
/**
* Decryption has a default fallback for the deprecated algorithm
*
* @param {*} encryptedHex
* @param {*} secret
*/
const decrypt = function(encryptedHex, secret) {
const encryptedArray = encryptedHex.split(":");
// maintain backwards compatibility
if (encryptedArray.length === 1) {
return decryptAes256Ctr(encryptedArray[0], secret);
}
const iv = new Buffer.from(encryptedArray[0], "hex");
const encrypted = new Buffer.from(encryptedArray[1], "hex");
const decipher = crypto.createDecipheriv(algorithm, secret, iv);
const decrypted = decipher.update(encrypted);
const clearText = Buffer.concat([decrypted, decipher.final()]).toString();
return clearText;
};
const fieldEncryption = function(schema, options) {
if (!options || !options.secret) {
throw new Error("missing required secret");
}
const useAes256Ctr = options.useAes256Ctr || false;
const fieldsToEncrypt = options.fields || [];
const hash = crypto.createHash("sha256");
hash.update(options.secret);
const secret = useAes256Ctr ? options.secret : hash.digest("hex").substring(0, 32);
const encryptionStrategy = useAes256Ctr ? encryptAes256Ctr : encrypt;
// add marker fields to schema
for (let field of fieldsToEncrypt) {
const encryptedFieldName = encryptedFieldNamePrefix + field;
const encryptedFieldData = encryptedFieldName + encryptedFieldDataSuffix;
const schemaField = {};
schemaField[encryptedFieldName] = { type: Boolean };
schemaField[encryptedFieldData] = { type: String };
schema.add(schemaField);
}
//
// local methods
//
// for mongoose 4/5 compatibility
const defaultNext = function defaultNext(err) {
if (err) {
throw err;
}
};
function getCompatitibleNextFunc(next) {
if (typeof next !== "function") {
return defaultNext;
}
return next;
}
function getCompatibleData(next, data) {
// in mongoose5, 'data' field is undefined
if (!data) {
return next;
}
return data;
}
function encryptFields(obj, fields, secret) {
for (let field of fields) {
const encryptedFieldName = encryptedFieldNamePrefix + field;
const encryptedFieldData = encryptedFieldName + encryptedFieldDataSuffix;
const fieldValue = obj[field];
if (!obj[encryptedFieldName] && fieldValue) {
if (typeof fieldValue === "string") {
// handle strings separately to maintain searchability
const value = encryptionStrategy(fieldValue, secret);
obj[field] = value;
} else {
const value = encryptionStrategy(JSON.stringify(fieldValue), secret);
obj[field] = undefined;
obj[encryptedFieldData] = value;
}
obj[encryptedFieldName] = true;
}
}
}
function decryptFields(obj, fields, secret) {
for (let field of fields) {
const encryptedFieldName = encryptedFieldNamePrefix + field;
const encryptedFieldData = encryptedFieldName + encryptedFieldDataSuffix;
if (obj[encryptedFieldName]) {
if (obj[encryptedFieldData]) {
const encryptedValue = obj[encryptedFieldData];
obj[field] = JSON.parse(decrypt(encryptedValue, secret));
obj[encryptedFieldName] = false;
obj[encryptedFieldData] = "";
} else {
// If the field has been marked to not be retrieved, it'll be undefined
if (obj[field]) {
// handle strings separately to maintain searchability
const encryptedValue = obj[field];
obj[field] = decrypt(encryptedValue, secret);
obj[encryptedFieldName] = false;
}
}
}
}
}
function updateHook(_next) {
const next = getCompatitibleNextFunc(_next);
for (let field of fieldsToEncrypt) {
const encryptedFieldName = encryptedFieldNamePrefix + field;
this._update.$set = this._update.$set || {};
const plainTextValue = this._update.$set[field] || this._update[field];
const encryptedFieldValue = this._update.$set[encryptedFieldName] || this._update[encryptedFieldName];
if (!encryptedFieldValue && plainTextValue) {
let updateObj = {};
if (typeof plainTextValue === "string" || plainTextValue instanceof String) {
const encryptedData = encryptionStrategy(plainTextValue, secret);
updateObj[field] = encryptedData;
updateObj[encryptedFieldName] = true;
} else {
const encryptedFieldData = encryptedFieldName + encryptedFieldDataSuffix;
updateObj[field] = undefined;
updateObj[encryptedFieldData] = encryptionStrategy(JSON.stringify(plainTextValue), secret);
updateObj[encryptedFieldName] = true;
}
this.update({}, Object.keys(this._update.$set).length > 0 ? { $set: updateObj } : updateObj);
}
}
next();
}
//
// static methods
//
schema.methods.stripEncryptionFieldMarkers = function() {
for (let field of fieldsToEncrypt) {
let encryptedFieldName = encryptedFieldNamePrefix + field;
let encryptedFieldData = encryptedFieldName + encryptedFieldDataSuffix;
this.set(encryptedFieldName, undefined);
this.set(encryptedFieldData, undefined);
}
};
schema.methods.decryptFieldsSync = function() {
decryptFields(this, fieldsToEncrypt, secret);
};
schema.methods.encryptFieldsSync = function() {
encryptFields(this, fieldsToEncrypt, secret);
};
//
// hooks
//
schema.post("init", function(_next, _data) {
const next = getCompatitibleNextFunc(_next);
const data = getCompatibleData(_next, _data);
try {
decryptFields(data, fieldsToEncrypt, secret);
next();
} catch (err) {
next(err);
}
});
schema.pre("save", function(_next) {
const next = getCompatitibleNextFunc(_next);
try {
encryptFields(this, fieldsToEncrypt, secret);
next();
} catch (err) {
next(err);
}
});
schema.pre("findOneAndUpdate", updateHook);
schema.pre("update", updateHook);
};
module.exports.fieldEncryption = fieldEncryption;
module.exports.encrypt = encrypt;
module.exports.decrypt = decrypt;
module.exports.encryptAes256Ctr = encryptAes256Ctr;