-
Notifications
You must be signed in to change notification settings - Fork 6
/
decode-browser.js
59 lines (52 loc) · 2.04 KB
/
decode-browser.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
const MAX_RETRIES = 10;
async function getQRCodeData(dataUrl) {
const codeReader = new ZXing.BrowserQRCodeReader();
for (let i = 0; i < MAX_RETRIES; i++) {
try {
const result = await codeReader.decodeFromImageUrl(dataUrl);
return result.text;
} catch (e) {
console.error(`Error decoding QR code (attempt ${i + 1}):`, e.message);
}
}
throw new Error('Failed to decode QR code');
}
async function decodeBrowser(dataUrl, password) {
try {
const qrCodeData = await getQRCodeData(dataUrl);
const encryptedData = qrCodeData;
const decrypted = password ? CryptoJS.AES.decrypt(encryptedData, password).toString(CryptoJS.enc.Utf8) : encryptedData;
const decodedData = JSON.parse(decrypted);
return decodedData;
} catch (e) {
console.error('Error decoding data:', e.message);
throw e;
}
}
function handleFileSelect() {
const inputFile = document.getElementById('input-file').files[0];
if (inputFile) {
document.getElementById('choose_file').textContent = `Selected file: ${inputFile.name}`;
} else {
document.getElementById('choose_file').textContent = 'No file selected';
}
}
function handleDecode() {
const inputFile = document.getElementById('input-file').files[0];
const password = document.getElementById('password').value;
const reader = new FileReader();
reader.onload = async (event) => {
const dataUrl = event.target.result;
try {
const decodedData = await decodeBrowser(dataUrl, password);
document.getElementById('result-filename').textContent = `Filename: ${decodedData.filename}`;
document.getElementById('result-message').textContent = `Message: ${decodedData.data}`;
} catch (e) {
document.getElementById('result-filename').textContent = 'Error decoding the file';
document.getElementById('result-message').textContent = '';
}
};
reader.readAsDataURL(inputFile);
}
document.getElementById('input-file').addEventListener('change', handleFileSelect);
document.getElementById('decode').addEventListener('click', handleDecode);