-
Notifications
You must be signed in to change notification settings - Fork 0
/
content.js
321 lines (279 loc) · 10.9 KB
/
content.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
// MIT License
// Copyright (c) [2024] [github\babadue]
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'encryptEmail') {
console.log("content.js encryptEmail");
// Find all span elements with an email attribute
const emailSpans = document.querySelectorAll('span[email]');
if (emailSpans.length > 0) {
// Get the last span element in the NodeList
const lastEmailSpan = emailSpans[emailSpans.length - 1];
const recipientEmail = lastEmailSpan.getAttribute('email');
console.log("Found recipient email:", recipientEmail);
// Fetch the public key using the extracted recipient email
fetch(`http://localhost:5000/getPublicKey?email=${encodeURIComponent(recipientEmail)}`)
.then(response => response.text())
.then(publicKey => {
console.log("Fetched Public Key:", publicKey);
const composeBody = document.querySelector('div[aria-label="Message Body"]');
const text = composeBody.innerText;
encryptText(text, publicKey); // Encrypt the message body with the fetched public key
})
.catch(error => console.error("Error fetching public key:", error));
} else {
console.error("No recipient email found.");
}
} else if (message.action === 'decryptEmail') {
// Code to write the body of the email
console.log('content decryptEmail:');
fetch(chrome.runtime.getURL("keys/private_key.pem"))
.then(response => response.text())
.then(privateKey => {
console.log("decryptEmail Private Key:", privateKey);
const emailBody = document.querySelector('div.a3s.aiL div[dir="ltr"]')?.innerText || "No body found";
console.log('decryptEmail emailBody: ', emailBody);
decryptText(emailBody, privateKey);
})
.catch(error => console.error("Error decryptEmail the private key:", error));
}// No need to call sendResponse if no response is needed.
});
// Encrypt button action
async function encryptText(text, publicKey) {
console.log("encryptText text: ", text);
console.log("encryptText publicKey: ", publicKey);
// 1. Generate AES key
const aesKey = await generateAESKey();
console.log("encryptText aesKey: ", aesKey);
// 2. Encrypt AES key with RSA
const encryptedAESKey = await encryptAESKey(aesKey, publicKey);
console.log("encryptText encryptedAESKey: ", encryptedAESKey);
// 3. Encrypt the message with AES
const { iv, encryptedMessage } = await encryptMessageWithAES(aesKey, text);
// 4. Convert both to base64
const encryptedAESKeyBase64 = arrayBufferToBase64(encryptedAESKey);
const ivBase64 = arrayBufferToBase64(iv);
const encryptedMessageBase64 = arrayBufferToBase64(encryptedMessage);
// 5. Combine the encrypted AES key, IV, and message
const combined = `${encryptedAESKeyBase64}:${ivBase64}:${encryptedMessageBase64}`;
// combinedEncodedData = combined;
console.log("Combined encrypted encoded text:", combined);
document.querySelector('div[aria-label="Message Body"]').innerText = combined;
}
// Generate AES key
async function generateAESKey() {
return await window.crypto.subtle.generateKey(
{
name: "AES-GCM",
length: 256
},
true,
["encrypt", "decrypt"]
);
}
// Encrypt the AES key with RSA
async function encryptAESKey(aesKey, publicKeyPem) {
console.log("encryptedAESKey aeskey: ", aesKey);
console.log("encryptedAESKey publicKeyPem: ", publicKeyPem);
const publicKey = await importPublicKey(publicKeyPem); // Import the PEM public key
console.log("encryptedAESKey publicKey: ", publicKey);
const exportedKey = await window.crypto.subtle.exportKey("raw", aesKey);
return await window.crypto.subtle.encrypt(
{
name: "RSA-OAEP"
},
publicKey,
exportedKey
);
}
// Encrypt the message with AES
async function encryptMessageWithAES(aesKey, message) {
const iv = window.crypto.getRandomValues(new Uint8Array(12)); // IV for AES-GCM
const encoder = new TextEncoder();
const encodedMessage = encoder.encode(message);
const encrypted = await window.crypto.subtle.encrypt(
{
name: "AES-GCM",
iv: iv
},
aesKey,
encodedMessage
);
return {
iv: iv,
encryptedMessage: encrypted
};
}
// Base64 encoding
function arrayBufferToBase64(buffer) {
const byteArray = new Uint8Array(buffer);
const byteString = String.fromCharCode.apply(null, byteArray);
return btoa(byteString);
}
// Base64 decoding
function base64ToArrayBuffer(base64) {
const byteString = atob(base64);
const byteArray = new Uint8Array(byteString.length);
for (let i = 0; i < byteString.length; i++) {
byteArray[i] = byteString.charCodeAt(i);
}
return byteArray.buffer;
}
// Helper function to convert PEM to ArrayBuffer
function pemToArrayBuffer(pem) {
const base64 = pem
.replace(/-----BEGIN [\w ]+-----/, "")
.replace(/-----END [\w ]+-----/, "")
.replace(/\s/g, '');
console.log("pemToArrayBuffer base64: ", base64);
return base64ToArrayBuffer(base64);
}
// Import the RSA public key
async function importPublicKey(pem) {
const keyData = pemToArrayBuffer(pem);
return window.crypto.subtle.importKey(
"spki", // Format for public keys
keyData,
{
name: "RSA-OAEP",
hash: { name: "SHA-256" }
},
true,
["encrypt"]
);
}
// Decrypt button action
async function decryptText(emailBody, priateKeyPem) {
console.log("decryptText emailBody: ", emailBody);
console.log("decryptText privateKeyPem: ", priateKeyPem);
const combinedText = emailBody;
const [encryptedAESKeyBase64, ivBase64, encryptedMessageBase64] = combinedText.split(":");
console.log("decryptText encryptedAESKeyBase64: ", encryptedAESKeyBase64);
console.log("decryptText ivBase64: ", ivBase64);
console.log("decryptText encryptedMessageBase64: ", encryptedMessageBase64);
// 1. Convert from base64 to ArrayBuffer
const encryptedAESKey = base64ToArrayBuffer(encryptedAESKeyBase64);
const iv = base64ToArrayBuffer(ivBase64);
const encryptedMessage = base64ToArrayBuffer(encryptedMessageBase64);
console.log("decryptText encryptedMessage: ", encryptedMessage);
// 2. Decrypt AES key with RSA
const aesKey = await decryptAESKey(encryptedAESKey, priateKeyPem);
console.log("decryptText aesKey: ", aesKey);
// 3. Decrypt the message with AES
const decryptedMessage = await decryptMessageWithAES(aesKey, iv, encryptedMessage);
console.log("Decrypted message:", decryptedMessage);
// Display the result in a popup window
displayText(decryptedMessage);
}
// Function to escape HTML special characters
function escapeHtml(text) {
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, (m) => map[m]);
}
function displayText(text)
{
// Open the popup window
const popup = window.open("", "Decrypted Email", "width=600,height=400");
// Ensure the document is open for writing
popup.document.open();
// Write HTML content to the popup
popup.document.write(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Decrypted Email</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
line-height: 1.6;
}
pre {
background-color: #f4f4f4;
border: 1px solid #ddd;
padding: 10px;
white-space: pre-wrap; /* Allows for text wrapping */
word-wrap: break-word; /* Ensures long lines break correctly */
}
</style>
</head>
<body>
<h1>Decrypted Email</h1>
<pre>${escapeHtml(text)}</pre>
</body>
</html>
`);
// Close the document to finish writing
popup.document.close();
}
// Decrypt the AES key with RSA
async function decryptAESKey(encryptedAESKey, privateKeyPem) {
console.log("decryptAESKey privateKeyPem:", privateKeyPem);
const privateKey = await importPrivateKey(privateKeyPem); // Import the PEM private key
console.log("decryptAESKey privateKey:", privateKey);
const decryptedKey = await window.crypto.subtle.decrypt(
{
name: "RSA-OAEP"
},
privateKey,
encryptedAESKey
);
return window.crypto.subtle.importKey(
"raw",
decryptedKey,
{ name: "AES-GCM" },
true,
["decrypt"]
);
}
// Decrypt the message with AES
async function decryptMessageWithAES(aesKey, iv, encryptedMessage) {
const decrypted = await window.crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: iv
},
aesKey,
encryptedMessage
);
const decoder = new TextDecoder();
return decoder.decode(decrypted);
}
// Import the RSA private key
async function importPrivateKey(pem) {
console.log("importPrivateKey pem:", pem);
const keyData = pemToArrayBuffer(pem);
console.log("importPrivateKey keyData:", keyData);
return window.crypto.subtle.importKey(
"pkcs8", // Format for private keys
keyData,
{
name: "RSA-OAEP",
hash: { name: "SHA-256" }
},
true,
["decrypt"] // For descryption
);
}