-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
236 lines (202 loc) · 7.94 KB
/
utils.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
const fs = require('fs');
const Crypto = require('crypto');
const NodeRSA = require('node-rsa');
const accountsPath = './base/accounts.json';
const Header = require('./Models/Header.js');
const Ledger = require('./Ledger.js');
const extensions = {
file: '.txt',
key: '.pem'
};
const path = {
keys: './keys/',
files: './files/',
storage: './storage/'
};
const Utils = {
buildFile: function(file, fileName = null, isKey = false) {
return new Promise((resolve, reject) => {
if ( fileName === null ) {
fileName = Crypto.createHash('md5').update(file).digest('hex');
}
fileName = isKey ? path.keys + fileName + extensions.key : path.files + fileName + extensions.file;
try {
fs.writeFile( fileName, file, function (err) {
if (err) throw err;
console.log(fileName, 'salvo!');
resolve(fileName);
});
} catch( err ) {
reject(err)
}
});
},
buildHeader: function(file, user, time = null) {
let _this = this;
return new Promise((resolve, reject) => {
let result = {
header: Header,
file: path.storage + file
};
if (fs.existsSync(path.storage + file)) {
result.header.owner = user;
result.header.oldHash = null;
result.header.time = null;
result.header.user = user;
result.header.date = new Date();
resolve(result);
} else {
Ledger.find(file)
.then( function(res) {
let oldTransaction = res;
if ( !_this.validateAccount(user) ) {
return false;
}
console.log('Destruindo chave do usuário');
_this.destroyFile(res.key)
.then(function(res) {
result.header.owner = time === null ? user : oldTransaction.owner;
result.header.oldHash = oldTransaction.hash;
result.header.time = (oldTransaction.time !== null ? oldTransaction.time : (time === null ? null : new Date(time)));
result.header.user = user;
result.header.date = new Date();
result.file = oldTransaction.file;
resolve(result);
})
.catch(function(err) {
console.error(err);
});
})
.catch(function(err) {
console.error(err);
});
}
});
},
buildHeaderData: function(content) {
return ('#!!HEADER!!#' + content + '/!!HEADER!!/');
},
decrypt: function(file, key, user) {
const _this = this;
console.log('Iniciando o processo para decifrar');
return new Promise((resolve, reject) => {
if( !_this.validateAccount(user) ) {
reject('Usuário inválido');
return false;
}
console.log('Obtendo objeto intelectual');
_this.readFile(file)
.then(function(res) {
const encrypted = res.toString('utf8');
console.log('Obtendo chave');
_this.readFile(key)
.then(function(res) {
const secureKey = res.toString('utf8');
try {
const newKey = new NodeRSA();
newKey.importKey(secureKey);
console.log('Decifrando objeto intelectual');
const decrypted = newKey.decrypt(encrypted, 'utf8');
const header = _this.readHeader(decrypted);
if ( _this.validateUser(header, user) ) {
resolve(decrypted);
} else {
_this.destroyFile(key)
.then(function(res) {
console.log(res);
})
.catch(function(err){
console.error(err);
});
reject('Usuário inválido');
}
} catch( err ) {
reject(err);
}
})
.catch(function(err) {
reject(err);
});
})
.catch(function(err) {
reject(err);
});
})
},
destroyFile: function(file) {
return new Promise((resolve, reject) => {
try {
console.log('Destruindo arquivo');
fs.unlink(file, function (err) {
if (err) throw err;
resolve('Arquivo deletado!');
});
} catch( err ) {
reject(err);
}
});
},
encrypt: function(content) {
const _this = this;
return new Promise((resolve, reject) => {
const key = new NodeRSA({b: 2048});
const privateKey = key.exportKey('pkcs1-private-prem');
const encrypted = key.encrypt(content, 'base64');
_this.buildFile(encrypted)
.then(function(res) {
const encryptedFileName = res;
_this.buildFile(privateKey, null, true)
.then(function(res) {
const result = {
key: res,
file: encryptedFileName,
hash: Crypto.createHash('md5').update(content).digest('hex')
};
resolve(result);
})
.catch(function(err) {
console.error(err);
reject(err);
});
})
.catch(function(err) {
console.error(err);
reject(err);
});
});
},
readFile: function(file) {
console.log('Executando leitura do arquivo!');
return new Promise((resolve, reject) => {
fs.readFile(file, function(err, data) {
if (err) reject(err);
data = data.toString('utf8');
resolve(data);
});
});
},
readHeader: function(content) {
console.log('Obtendo cabeçalho do arquivo.');
const regex = new RegExp('#!!HEADER!!#(.*?)\/!!HEADER!!\/');
if ( regex.test(content) ) {
header = regex.exec(content)[0].replace('#!!HEADER!!#', '').replace('/!!HEADER!!/', '');
return JSON.parse(header);
} else {
console.error('Header not found');
}
},
validateAccount: function(account) {
console.log('Validando usuário');
let accounts = require(accountsPath);
return accounts.find((element) => (element === account));
},
validateUser: function(header, user) {
console.log('Validando utilizador');
return header.user === user;
},
validateOwner: function(header, user) {
console.log('Validando utilizador');
return header.owner === user;
}
};
module.exports = Utils;