Repository navigation
Expand file tree
/
Copy pathxorEncryptClass.java
More file actions
68 lines (65 loc) · 2.46 KB
/
Copy pathxorEncryptClass.java
File metadata and controls
68 lines (65 loc) · 2.46 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
import java.io.*;
import java.nio.file.Files;
public class xorEncryptClass {
public static byte[] xorEncrypt(byte[] input, byte key) {
byte[] output = new byte[input.length];
for (int i = 0; i < input.length; i++) {
output[i] = (byte) (input[i] ^ key);
}
return output;
}
public static void encryptFile(String inputFile, String key) {
File file = new File(inputFile);
if(!file.exists()) {
System.out.println("File not found!" + inputFile);
return;
}
if(file.length() == 0) {
System.out.println("Empty file!" + inputFile);
return;
}
if(file.length() > 1100000000) {
System.out.println("File too large!" + inputFile);
return;
}
try {
byte[] inputData = Files.readAllBytes(new File(inputFile).toPath());
byte[] encryptedData = inputData;
for(int i=0; i<key.length(); i++) {
encryptedData = xorEncrypt(encryptedData, (byte) key.charAt(i));
}
System.out.println("Encryption done! "+inputFile);
try{
Files.write(new File(inputFile + ".rewar").toPath(), encryptedData);
Files.delete(new File(inputFile).toPath());
}catch(Exception e){
System.out.println("Error in write/delete while encrypting file: "+e);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void decryptFile(String inputFile, String key) {
if(!inputFile.endsWith(".rewar")) {
System.out.println("Invalid file format!");
return;
}
try {
byte[] inputData = Files.readAllBytes(new File(inputFile).toPath());
byte[] decryptedData = inputData;
for(int i=key.length()-1; i>=0; i--) {
decryptedData = xorEncrypt(decryptedData, (byte) key.charAt(i));
}
System.out.println("Decryption done! " + inputFile);
String outputFile = inputFile.substring(0, inputFile.length() - 6);
try{
Files.write(new File(outputFile).toPath(), decryptedData);
Files.delete(new File(inputFile).toPath());
}catch(Exception e){
System.out.println("Error in write/delete while decrypting file: "+e);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}