-
Notifications
You must be signed in to change notification settings - Fork 120
Expand file tree
/
Copy pathAffineCipher.java
More file actions
64 lines (53 loc) · 1.2 KB
/
AffineCipher.java
File metadata and controls
64 lines (53 loc) · 1.2 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
public class AffineCipher {
static int a = 17;
static int b = 20;
static String encryptMessage(char[] msg)
{
String cipher = "";
for (int i = 0; i < msg.length; i++)
{
if (msg[i] != ' ')
{
cipher = cipher + (char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A');
}
else
{
cipher += msg[i];
}
}
return cipher;
}
static String decryptCipher(String cipher)
{
String msg = "";
int a_inv = 0;
int flag = 0;
for (int i = 0; i < 26; i++)
{
flag = (a * i) % 26;
if (flag == 1)
{
a_inv = i;
}
}
for (int i = 0; i < cipher.length(); i++)
{
if (cipher.charAt(i) != ' ')
{
msg = msg + (char) (((a_inv *((cipher.charAt(i) + 'A' - b)) % 26)) + 'A');
}
else
{
msg += cipher.charAt(i);
}
}
return msg;
}
public static void main(String[] args)
{
String msg = "HELLO";
String cipherText = encryptMessage(msg.toCharArray());
System.out.println("Encrypted Message is : " + cipherText);
System.out.println("Decrypted Message is: " + decryptCipher(cipherText));
}
}