-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstarwaveCrypto.js
248 lines (223 loc) · 7.87 KB
/
starwaveCrypto.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
239
240
241
242
243
244
245
246
247
248
/**
* Encryption protocol for starwave
* new fields in message object:
* encrypted - means that message is encrypted
* publicKey - public key of the sender which wants to make crypted tunnel
* Using secp256k1 curve and aes256 algorithm as default
*
* This module uses elliptic library for creating keypair and crypto-js to encrypt/decrypt message
* https://github.com/indutny/elliptic
* https://github.com/brix/crypto-js
*/
'use strict';
//unify browser and node
if (typeof _this ==='undefined') {
var _this = this;
}
if (_this.window === undefined){
_this.elliptic = require('elliptic');
_this.CryptoJS = require('crypto-js');
}
const SWCRYPTO_CONNECTION_MESSAGE_TYPE = 'DH-CONNECTION';
/**
* Crypto addon for StarWave Protocol
*/
class StarwaveCrypto {
constructor(starwaveProtocolObject, secretKeysKeyring, curve = 'secp256k1') {
if (_this.window === undefined){
this.elliptic = require('elliptic');
this.CryptoJS = require('crypto-js');
} else {
this.elliptic = elliptic;
this.CryptoJS = CryptoJS;
}
let that = this;
// EСDH object
this.ec = new elliptic.ec(curve);
this.keyObject = this.ec.genKeyPair();
this.public = this.generateKeys();
this.starwave = starwaveProtocolObject;
this.secretKeys = secretKeysKeyring;
this.curve = curve;
this._connectionsCallbacks = {};
starwaveProtocolObject.registerMessageHandler(SWCRYPTO_CONNECTION_MESSAGE_TYPE, function (message) {
that.handleIncomingMessage(message);
return true;
});
starwaveProtocolObject.registerMessageHandler('', function (message) {
that.handleIncomingMessage(message);
return false;
});
};
/**
* Get public key object for Diffie-Hellman
* @returns {*}
*/
generateKeys(keyObject = this.keyObject) {
return keyObject.getPublic(true, 'hex');
}
/**
* Create secret key based on external public key
* @param {string} externalPublic
* @returns {string}
*/
createSecret(externalPublic) {
let secret;
try {
let pub = this.ec.curve.decodePoint(externalPublic, 'hex'); //get public key object from string
secret = this.keyObject.derive(pub);
secret = secret.toString(16);
} catch (err) {
console.log('Error: Can not create secret key ' + err); //if externalPublic is wrong
}
return secret;
};
/**
* Encrypts data
* @param {string} data Data to encrypt
* @param {string} secret Encryption secret
* @returns {string}
*/
cipherData(data, secret) {
let encrypted = CryptoJS.AES.encrypt(data, secret).toString(); //base64
let b64 = CryptoJS.enc.Base64.parse(encrypted);//object
encrypted = b64.toString(CryptoJS.enc.Hex);//hex
return encrypted;
}
/**
* Decripts data
* @param {string} encryptedData Encrypted data source
* @param {string} secret Encryption secret
* @returns {string}
*/
decipherData(encryptedData, secret) {
let data;
try {
//unpack from hex to native base64 and to object
let b64 = CryptoJS.enc.Hex.parse(encryptedData);
let bytes = b64.toString(CryptoJS.enc.Base64);
data = CryptoJS.AES.decrypt(bytes, secret);
data = data.toString(CryptoJS.enc.Utf8);
} catch (e) {
console.log('Error decrypting data: ' + e)
}
return data;
}
/**
* Decrypts data field in message
* @param {object} message Message object
* @returns {*}
*/
decipherMessage(message) {
let decryptedData;
//if message didn't encrypted, return data
if(!message.encrypted) {
return decryptedData = message.data;
}
//if we have secret key associated with this socket than we have the tunnel
if(this.secretKeys[message.sender]) {
decryptedData = this.decipherData(message.data, this.secretKeys[message.sender]);
if(decryptedData) {
//try to parse json
try {
decryptedData = JSON.parse(decryptedData)
} catch (e) {
console.log("Error: An error occurred while parsing decrypted text: " + e);
}
}
message.original = message.data;
message.data = decryptedData;
delete message.encrypted;
}
return decryptedData;
}
/**
* Encrypts data field in message
* @param {object} message Message object
* @returns {*}
*/
cipherMessage(message) {
let cryptedData;
//should be assotiated secret key and check that message has not been already encrypted
if(this.secretKeys[message.reciver] && !message.encrypted) {
cryptedData = this.cipherData(JSON.stringify(message.data), this.secretKeys[message.reciver]);
message.encrypted = true;
message.data = cryptedData;
}
return cryptedData;
}
/**
* Processes incoming message
* @param message
* @returns {*}
*/
handleIncomingMessage(message) {
//watch if the message has Public key field then the message is only for sending the key
if(message.publicKey) {
let sc = this.createSecret(message.publicKey); //exclude situation with exception on wrong public
//if we don't have secret key then we save sender publickey and create secret and send our public to make connection
if((!this.secretKeys[message.sender] && sc) || this.secretKeys[message.sender] !== sc) {
this.makeConnection(message.sender);
}
if(sc) {
this.secretKeys[message.sender] = sc;
if(this._connectionsCallbacks[message.sender]) {
this._connectionsCallbacks[message.sender](message.sender, sc);
delete this._connectionsCallbacks[message.sender];
}
}
delete message.publicKey;
return 0;
}
message.data = this.decipherMessage(message); //undefined if we have errors
return 1;
}
/**
* Make encrypted connection
* @param {string} messageBus Connection address
* @param {(function(string, string))} cb Connection callback 1 - receiver, 2 - secret key
* @return {StarwaveCrypto}
*/
makeConnection(messageBus, cb) {
let that = this;
if(cb) {
this._connectionsCallbacks[messageBus] = cb;
//Call callback if key already created
if(this.secretKeys[messageBus]) {
setTimeout(function () {
cb(messageBus, that.secretKeys[messageBus]);
}, 1);
}
}
let message = this.starwave.createMessage('{}', messageBus, undefined, SWCRYPTO_CONNECTION_MESSAGE_TYPE);
message.publicKey = this.public;
this.starwave.sendMessage(message);
return this;
}
/**
* Send message using encryption protocol
* @param {object} message Data for sending
* @returns {number} Status
*/
sendMessage(message) {
//check if we have secret key for reciver
let sk = this.secretKeys[message.reciver]; //secret key
if(sk) {
if(this.cipherMessage(message)) {
this.starwave.sendMessage(message);
return message;
} else {
console.log("Error: Can't cipher message");
return 2;
}
}
else {
console.log(`Error: There is no secret key for address: ${message.reciver}`);
return 1;
}
}
}
//unify browser and node
if (this.window === undefined){
module.exports = StarwaveCrypto;
}