-
Notifications
You must be signed in to change notification settings - Fork 13
/
XORCipher.java
88 lines (71 loc) · 2.54 KB
/
XORCipher.java
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
/*********
-*- Made by VoxelPixel
-*- For YouTube Tutorial
-*- https://github.com/VoxelPixel
-*- Support me on Patreon: https://www.patreon.com/voxelpixel
*********/
import java.util.Scanner;
public class XORCipher {
private static Scanner in;
public static void main(String[] args){
in = new Scanner(System.in);
System.out.print("1. Encryption\n2. Decryption\nChoose(1,2): ");
int choice = in.nextInt();
in.nextLine();
if(choice == 1){
System.out.println("---Encryption---");
cipherEncryption();
} else if (choice == 2){
System.out.println("---Decryption---");
cipherDecryption();
} else {
System.out.println("Invalid Choice");
}
}
private static void cipherDecryption() {
System.out.print("Enter message: ");
String msg = in.nextLine();
System.out.print("Enter key: ");
String key = in.nextLine();
String hexToDeci = "";
for (int i = 0; i < msg.length()-1; i+=2) {
// splitting hex into a pair of two
String output = msg.substring(i, (i+2));
int decimal = Integer.parseInt(output, 16);
hexToDeci += (char)decimal;
}
// decryption
String decrypText = "";
int keyItr = 0;
for (int i = 0; i < hexToDeci.length(); i++) {
// XOR Operation
int temp = hexToDeci.charAt(i) ^ key.charAt(keyItr);
decrypText += (char)temp;
keyItr++;
if(keyItr >= key.length()){
// once all of key's letters are used, repeat the key
keyItr = 0;
}
}
System.out.println("Decrypted Text: " + decrypText);
}
private static void cipherEncryption() {
System.out.print("Enter message: ");
String msg = in.nextLine();
System.out.print("Enter key: ");
String key = in.nextLine();
String encrypHexa = "";
int keyItr = 0;
for (int i = 0; i < msg.length(); i++) {
// XOR Operation
int temp = msg.charAt(i) ^ key.charAt(keyItr);
encrypHexa += String.format("%02x", (byte)temp);
keyItr++;
if(keyItr >= key.length()){
// once all of key's letters are used, repeat the key
keyItr = 0;
}
}
System.out.println("Encrypted Text: " + encrypHexa);
}
}