-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
83 lines (73 loc) · 1.93 KB
/
index.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
'use strict';
const util = require('./util');
//const LZString = require('lz-string');
function encrypt(data, key, token, time){
var md5 = util.md5(time, token);
var data = util.encrypt(data, key, md5);
//return LZString.compress(data);
return data;
}
function decrypt(data, key, token, time){
//var body = LZString.decompress(data);
var body = data;
var md5 = util.md5(time, token);
return util.decrypt(body, key, md5);
}
class Multi {
constructor(privateKey, token, trace){
this.token = token;
this.privateKey = privateKey;
this.trace = trace;
this.msg = {
time: new Date().getTime(),
data: []
}
if ( token ) this.msg.token = token;
if ( trace ) this.msg.trace = trace;
}
encode(msg){
var item = {};
for ( var key in msg ){
item[key] = msg[key];
}
this.msg.data.push(item);
return this;
}
done(){
if ( this.token ){
this.msg.data = encrypt(JSON.stringify(this.msg.data), this.privateKey, this.token, this.msg.time);
}
return this.msg;
}
}
class Protocol {
constructor(privateKey, token){
if ( !privateKey || privateKey.length != 32) throw new Error('Invalid key length, must be 32 bytes!');
this.privateKey = privateKey;
if ( token ) this.token = token;
}
encode(msg){
msg.time = new Date().getTime();
if ( !msg.token && this.token ) msg.token = this.token;
if ( msg.token ) {
msg.data = encrypt(JSON.stringify(msg.data), this.privateKey, msg.token, msg.time);
}
return msg;
}
decode(msg){
if ( !msg.token ) {
return msg;
}
var data = decrypt(msg.data, this.privateKey, msg.token, msg.time);
msg.data = JSON.parse(data);
return msg;
}
multi(token){
return new Multi(this.privateKey, token || this.token);
}
}
function createProtocol(key, token){
var privateKey = util.md5(key, token);
return new Protocol(privateKey, token);
}
module.exports = createProtocol;