-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxorFromFile.js
76 lines (64 loc) · 2.17 KB
/
xorFromFile.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
/* The script implements a console interface for encoding and decoding text using the XOR method using the specified encryption key and optionally saving the results to a text file. The script supports input of Cyrillic languages. */
const fs = require('fs');
const readline = require('readline');
const os = require('os');
const rl = readline.createInterface({
input: fs.createReadStream('input.txt'),
output: process.stdout,
});
// Key from 0 to 65535
const encryptionKey = 12345;
// Function for working with text
function processText() {
rl.on('line', (text) => {
const isEncoded = isXOREncoded(text);
const result = isEncoded ? decodeText(text, encryptionKey) : encodeText(text, encryptionKey);
console.log(result);
writeToOutputFile(result);
});
rl.on('close', () => {
console.log('File processing complete.');
});
}
// Function for decoding XOR text
function decodeText(encodedText, key) {
let decodedText = '';
for (let i = 0; i < encodedText.length; i += 4) {
const chunk = encodedText.substring(i, i + 4);
const decodedChunk = parseInt(chunk, 16) ^ key;
decodedText += String.fromCharCode(decodedChunk);
}
return decodedText;
}
// Function for encoding XOR text
function encodeText(text, key) {
let encodedText = '';
for (let i = 0; i < text.length; i++) {
const charCode = text.charCodeAt(i);
const encodedChunk = (charCode ^ key).toString(16).padStart(4, '0');
encodedText += encodedChunk;
}
return encodedText;
}
// Checks if the text is an encrypted XOR, checks for 16-bit number format
function isXOREncoded(str) {
return /^[0-9a-fA-F]{4,}$/i.test(str);
}
// Writes text to the output.txt file
async function writeToOutputFile(text) {
try {
await fs.promises.appendFile('output.txt', text, 'utf8');
} catch (err) {
console.error('Error writing to file output.txt:', err);
}
}
// If the file exists, delete it
function deleteTextfile() {
const filePath = 'output.txt';
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
}
}
// Start the text processing process
deleteTextfile();
processText();