-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEndtoEnd.js
80 lines (80 loc) · 2.07 KB
/
EndtoEnd.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
const key = crypto.subtle
.generateKey(
{
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: "SHA-256",
},
false,
["encrypt", "decrypt"]
)
.then((k) => {
console.log('keys generated')
return k;
});
const pubKeys = {};
onmessage = async function (e) {
const data = e.data;
const opr = data.operation;
if (opr == 0) { //export the pub key
const publicKey = await crypto.subtle.exportKey(
"jwk",
(
await key
).publicKey
);
self.postMessage({ operation: 0, key: publicKey });
} else if (opr == 1) { //import the pub key
if (!data.key){
delete pubKeys[data.server+data.id]
return
}
const publicKey = await crypto.subtle.importKey(
"jwk",
{
kty: "RSA",
n: data.key,
e: "AQAB",
ext: true,
key_ops: ["encrypt"],
},
{ name: "RSA-OAEP", hash: "SHA-256" },
true,
["encrypt"]
);
pubKeys[data.server + data.id] = publicKey;
console.log("pub key set for " + data.server + data.id);
} else if (opr == 2) { //encrypt msg
if (data.server + data.id in pubKeys) {
// encrypt using the publicKey by updating the msg key
data['present']=true
const msgbuffer = new TextEncoder().encode(data.msg);
const encmsgbuffer = await crypto.subtle.encrypt(
{ name: "RSA-OAEP" },
pubKeys[data.server + data.id],
msgbuffer
);
data.msg = btoa(String.fromCharCode(...new Uint8Array(encmsgbuffer)));
self.postMessage(data);
} else {
data['present']=false
self.postMessage(data);
}
} else if (opr == 3) { //decrypt msg
const encmsgbuffer = new Uint8Array(
atob(data.msg)
.split("")
.map((c) => c.charCodeAt(0))
);
const dcrptmsgbuffer = await crypto.subtle.decrypt(
{ name: "RSA-OAEP" },
(
await key
).privateKey,
encmsgbuffer
);
data.msg = new TextDecoder().decode(dcrptmsgbuffer);
self.postMessage(data);
}
};