-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
344 lines (295 loc) · 9.94 KB
/
app.js
File metadata and controls
344 lines (295 loc) · 9.94 KB
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
const fileInput = document.getElementById('fileInput');
const privateKeyInput = document.getElementById('privateKey');
const encryptBtn = document.getElementById('encryptBtn');
const decryptBtn = document.getElementById('decryptBtn');
const outputDiv = document.getElementById('output');
const selectedFileNameSpan = document.getElementById('selectedFileName');
const generateKeyBtn = document.getElementById('generateKeyBtn');
document.getElementById('privateKey').addEventListener('input', updateKeyStrengthIndicator)
function updateKeyStrengthIndicator() {
const privateKeyInput = document.getElementById('privateKey');
const indicator = document.getElementById('keyStrengthIndicator');
const key = privateKeyInput.value;
let strengthText = '';
if (key.length === 0) {
strengthText = 'Please enter a key';
} else {
const result = zxcvbn(key);
const score = result.score;
const feedback = result.feedback.warning || '';
switch (score) {
case 0:
strengthText = 'Very Weak';
break;
case 1:
strengthText = 'Weak';
break;
case 2:
strengthText = 'Moderate';
break;
case 3:
strengthText = 'Strong';
break;
case 4:
strengthText = 'Very Strong';
break;
}
}
indicator.textContent = `Key Strength: ${strengthText}`;
}
// Function to generate a secure random key
async function generateSecureKey() {
const length = 32; // Key length in bytes
const keyBuffer = new Uint8Array(length);
const crypto = window.crypto || window.msCrypto; // For legacy Microsoft Edge support
if (crypto) {
await crypto.getRandomValues(keyBuffer);
const keyHex = Array.from(keyBuffer)
.map(byte => byte.toString(16).padStart(2, '0'))
.join('');
return keyHex;
} else {
console.error('Web Crypto API is not supported in this browser.');
return null;
}
}
// Event listener for the generate key button
generateKeyBtn.addEventListener('click', async () => {
const randomKey = await generateSecureKey();
if (randomKey) {
privateKeyInput.value = randomKey;
updateKeyStrengthIndicator()
} else {
console.error('Failed to generate a secure random key.');
}
});
const togglePasswordVisibility = document.getElementById('togglePasswordVisibility');
const passwordVisibilityIcon = document.getElementById('passwordVisibilityIcon');
togglePasswordVisibility.addEventListener('click', () => {
const currentType = privateKeyInput.type;
privateKeyInput.type = currentType === 'password' ? 'text' : 'password';
passwordVisibilityIcon.classList.toggle('fa-eye');
passwordVisibilityIcon.classList.toggle('fa-eye-slash');
});
// JavaScript for handling file selection and displaying file name
document.getElementById('dragAndDropBox').addEventListener('click', function() {
document.getElementById('fileInput').click();
});
document.getElementById('dragAndDropBox').addEventListener('dragover', function(event) {
event.preventDefault();
});
document.getElementById('dragAndDropBox').addEventListener('drop', function(event) {
event.preventDefault();
const files = event.dataTransfer.files;
handleFiles(files);
});
document.getElementById('fileInput').addEventListener('change', function() {
handleFiles(this.files);
});
function handleFiles(files) {
const file = files[0];
if (file) {
fileInput.files = files; // This step is required to sync the files list with input for form submissions
selectedFileNameSpan.textContent = file.name; // Update the span with file name
handleFile(file);
}
}
function handleFile(file) {
if (file) {
selectedFileNameSpan.textContent = file.name; // Update the span with file name
// Check if the file is encrypted and toggle button classes accordingly
const isEncrypted = file.name.endsWith('.encrypted');
toggleButtonClasses(isEncrypted);
// Enable buttons
encryptBtn.disabled = false;
decryptBtn.disabled = false;
showOutput('', '');
} else {
// Disable buttons if no file is selected
encryptBtn.disabled = true;
decryptBtn.disabled = true;
}
}
// Add 'def' class to both buttons initially
encryptBtn.classList.add('def');
decryptBtn.classList.add('def');
// Event listeners for encrypt and decrypt buttons
encryptBtn.addEventListener('click', function() {
const file = fileInput.files[0];
encryptFile(file);
});
decryptBtn.addEventListener('click', function() {
const file = fileInput.files[0];
decryptFile(file);
});
async function encryptFile(file) {
const privateKey = privateKeyInput.value;
if (!file || !privateKey) {
showOutput('Please select a file and provide a private key.', 'danger');
return;
}
const fileBuffer = await readFileAsArrayBuffer(file);
const encryptedData = await encryptWithKey(fileBuffer, privateKey);
const encryptedBlob = new Blob([encryptedData], { type: 'application/octet-stream' });
const url = URL.createObjectURL(encryptedBlob);
const link = createDownloadLink(url, `${file.name}.encrypted`, 'Download Encrypted File');
showOutput(link, 'success');
clearFileInput();
// Toggle button classes
decryptBtn.classList.remove('btn-decrypt');
encryptBtn.classList.remove('btn-encrypt');
decryptBtn.classList.add('def');
encryptBtn.classList.add('def');
}
async function decryptFile(file) {
const privateKey = privateKeyInput.value;
if (!file || !privateKey) {
showOutput('Please select a file and provide a private key.', 'danger');
return;
}
const fileBuffer = await readFileAsArrayBuffer(file);
const decryptedData = await decryptWithKey(fileBuffer, privateKey);
const decryptedBlob = new Blob([decryptedData], { type: 'application/octet-stream' });
const url = URL.createObjectURL(decryptedBlob);
const link = createDownloadLink(url, `${file.name.replace(/\.encrypted$/, '')}`, 'Download Decrypted File');
showOutput(link, 'success');
clearFileInput();
// Toggle button classes
toggleButtonClasses(false);
decryptBtn.classList.add('def');
encryptBtn.classList.add('def');
}
function toggleButtonClasses(isEncrypted) {
if (isEncrypted) {
decryptBtn.classList.remove('def');
decryptBtn.classList.add('btn-decrypt');
encryptBtn.classList.add('def');
} else {
encryptBtn.classList.remove('def');
encryptBtn.classList.add('btn-encrypt');
decryptBtn.classList.add('def');
}
}
function readFileAsArrayBuffer(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject(reader.error); // Update this line to handle errors better.
reader.readAsArrayBuffer(file);
});
}
async function encryptWithKey(data, passphrase) {
const encoder = new TextEncoder();
const encodedPassphrase = encoder.encode(passphrase);
try {
const derivedKey = await window.crypto.subtle.importKey(
'raw',
encodedPassphrase,
{
name: 'PBKDF2',
},
false,
['deriveBits', 'deriveKey']
);
const salt = window.crypto.getRandomValues(new Uint8Array(16)); // Generate a random salt
const keyMaterial = await window.crypto.subtle.deriveKey(
{
name: 'PBKDF2',
salt: salt,
iterations: 100000,
hash: 'SHA-256',
},
derivedKey,
{ name: 'AES-GCM', length: 256 },
true,
['encrypt']
);
const iv = window.crypto.getRandomValues(new Uint8Array(12));
const encryptedData = await window.crypto.subtle.encrypt(
{
name: 'AES-GCM',
iv: iv,
},
keyMaterial,
data
);
const encryptedDataWithIV = new Uint8Array([...salt, ...iv, ...new Uint8Array(encryptedData)]);
return encryptedDataWithIV;
} catch (error) {
console.error('Error encrypting data:', error);
showOutput('Encryption failed. Please ensure you have entered the correct private key.', 'danger');
throw error;
}
}
async function decryptWithKey(data, passphrase) {
try {
const encoder = new TextEncoder();
const encodedPassphrase = encoder.encode(passphrase);
const derivedKey = await window.crypto.subtle.importKey(
'raw',
encodedPassphrase,
{
name: 'PBKDF2',
},
false,
['deriveBits', 'deriveKey']
);
const salt = data.slice(0, 16); // Extract salt from the encrypted data
const iv = data.slice(16, 28); // Extract IV from the encrypted data
const encryptedData = data.slice(28); // Extract encrypted data
const keyMaterial = await window.crypto.subtle.deriveKey(
{
name: 'PBKDF2',
salt: salt,
iterations: 100000,
hash: 'SHA-256',
},
derivedKey,
{ name: 'AES-GCM', length: 256 },
true,
['decrypt']
);
const decryptedData = await window.crypto.subtle.decrypt(
{
name: 'AES-GCM',
iv: iv,
},
keyMaterial,
encryptedData
);
return decryptedData;
} catch (error) {
console.error('Error decrypting data:', error);
showOutput('Decryption failed. Please ensure you have entered the correct private key.', 'danger');
throw error;
}
}
function createDownloadLink(url, fileName, linkText) {
try {
const link = document.createElement('a');
link.href = url;
link.download = fileName;
link.innerText = linkText;
return link;
} catch (error) {
console.error('Error creating download link:', error);
return null;
}
}
function showOutput(content, type) {
outputDiv.innerHTML = ''; // Clear existing content
const outputElement = document.createElement('div');
outputElement.classList.add(`alert`, `alert-${type}`);
// Check if content is already a DOM node
if (content instanceof Node) {
outputElement.appendChild(content);
} else {
outputElement.textContent = content;
}
outputDiv.appendChild(outputElement);
}
function clearFileInput() {
// Function to clear the file input and the displayed file name
fileInput.value = ''; // Clear input
selectedFileNameSpan.textContent = ''; // Clear file name display
}