This repository has been archived by the owner on Mar 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
240 lines (198 loc) · 8.14 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Ecncryption Chat</title>
<script src="https://cdn.jsdelivr.net/npm/idb@8/build/umd.js"></script>
<script>
function sendToServer(relativePath, content) {
return new Promise((resolve, reject) => {
try {
const sessionId = localStorage.getItem("sessionid");
if (!sessionId) return alert("please refresh window");
var req = new XMLHttpRequest();
req.open('POST', `${window.location.origin}/${relativePath}`);
req.setRequestHeader('sid', sessionId);
req.setRequestHeader('pkey', content);
req.onloadend = (ev) => {
resolve(req.response);
}
req.send(content);
}
catch (err) {
reject(err);
}
})
}
const dbName = 'keyDatabase';
const storeName = 'keys';
const version = 1;
const key = 'privt';
/*
function writeKeyToIDB(key) {
return new Promise((resolve, reject) => {
const request = indexedDB.open("keyDatabase", 2);
request.onerror = (err) => {
console.error(err);
};
request.onupgradeneeded = (event) => {
const db = event.target.result;
const objectStore = db.createObjectStore("keys", { keyPath: "keyType" });
objectStore.createIndex("key", "key", { unique: true });
objectStore.transaction.oncomplete = (event) => {
const keyObjStore = db
.transaction("keys", "readwrite")
.objectStore("keys");
keyObjStore.add({ keyType: 'prvt', key: "DJDHDJKHKJDHKFJSHFKJDSHFLKJDf" });
};
};
})
}
*/
function getDB() {
return new Promise(async (resolve, reject) => {
if (!('indexedDB' in window)) {
console.warn('IndexedDB not supported!');
return reject();
}
const db = await idb.openDB(dbName, version, {
upgrade(db, oldVersion, newVersion, transaction) {
const store = db.createObjectStore(storeName);
}
});
resolve(db);
});
}
async function writeKeyToIDB(cKey) {
try {
const db = await getDB();
if (!db) return;
const tx = db.transaction(storeName, 'readwrite');
const store = await tx.objectStore(storeName);
const value = await store.put(cKey, key);
await tx.done;
return true;
}
catch (err) {
console.error(err);
return false;
}
}
async function demo() {
const toSend = document.getElementById('txtinp').value;
if (!toSend) return alert("NO TEXT FOUND TO SEND!")
const encMsg = await encryptMessage("other", toSend);
recieve(encMsg);
}
async function recieve(message) { document.getElementById('displayDiv').innerText = await decryptMessage(message); }
// CRYPTO STUFF
// for simplicity and aesthetic
async function getPrivKey() {
return (await getDB())?.transaction(storeName).objectStore(storeName).get(key) || null;
}
async function createAndStoreKey() {
try {
const keyPair = await window.crypto.subtle.generateKey({
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256",
},
true,
["encrypt", "decrypt"]
);
const publicKey = await crypto.subtle.exportKey("jwk", keyPair.publicKey);
const privateKey = await crypto.subtle.exportKey("jwk", keyPair.privateKey);
writeKeyToIDB(privateKey);
// send public key to server
const response = await sendToServer('newKey', JSON.stringify(publicKey));
return true;
} catch (error) {
console.error("Error in storing key:", error);
return false;
}
}
// the public key of the OTHER USER
async function encryptMessage(otherUID, message) {
try {
var publicKeyRaw = await sendToServer('getpubkey', otherUID);
// TODO: REMOVE THIS WHEN PORTING!!!
if (!publicKeyRaw) {
localStorage.setItem('sessionid', crypto.randomUUID());
const rCreate = await createAndStoreKey();
if (!rCreate) return alert("ERROR");
publicKeyRaw = await sendToServer('getpubkey', otherUID);
}
const publicKeyJSON = JSON.parse(publicKeyRaw);
const encoder = new TextEncoder();
const encodedMessage = encoder.encode(message);
const publicKey = await window.crypto.subtle.importKey(
"jwk",
publicKeyJSON,
{
name: "RSA-OAEP",
hash: { name: "SHA-256" }, // Specify the hash used with RSA-OAEP
},
true,
["encrypt"], // Specify the operation that the imported key will be used for
);
const encryptedMessage = await window.crypto.subtle.encrypt(
{ name: "RSA-OAEP" },
publicKey,
encodedMessage
);
return encryptedMessage;
}
catch (err) {
console.error(err);
return null;
}
}
async function decryptMessage(encryptedMessage) {
const privateKeyRaw = await getPrivKey();
if (!privateKeyRaw) return alert("NO PRIVATE KEY");
// Correct algorithm to RSA-OAEP and import the private key
const privateKey = await window.crypto.subtle.importKey(
"jwk",
privateKeyRaw,
{
name: "RSA-OAEP",
hash: { name: "SHA-256" } // Hash must match the one used in encrypting
},
true,
["decrypt"] // Correct operation for the private key
);
// Decrypt the message with the private key
const decryptedMessage = await window.crypto.subtle.decrypt(
{ name: "RSA-OAEP" },
privateKey,
encryptedMessage
);
const decoder = new TextDecoder();
return decoder.decode(decryptedMessage);
}
// INITIAL THINGS
async function init() {
if (!("TextDecoder" in window)) return alert("Sorry, this browser does not support TextDecoder...");
if (!('indexedDB' in window)) return alert('IndexedDB not supported!');
if (!localStorage.getItem('sessionid')) {
localStorage.setItem('sessionid', crypto.randomUUID());
const storedKey = await createAndStoreKey();
if (!storedKey) return alert("KEY ERROR!!!");
}
else if (!(await getPrivKey())) {
// LOG OUT HERE
localStorage.removeItem('sessionid');
console.warn("ADD LOG OUT LOGIC HERE");
}
};
init();
</script>
</head>
<body>
<input type="text" id="txtinp">
<button onclick="demo()">send message</button>
<div id="displayDiv"></div>
</body>
</html>