-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaffineCipher.java
More file actions
76 lines (59 loc) · 2.2 KB
/
affineCipher.java
File metadata and controls
76 lines (59 loc) · 2.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
65
66
67
68
69
70
71
72
73
74
75
76
import java.util.*;
public class affineCipher {
private static int modInverse(int a, int mod){
for (int i = 1; i < mod; i++){
if (((a % mod) * (i % mod)) % mod == 1){
return i;
}
}
return -1;
}
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("1. Encrypt");
System.out.println("2. Decrypt");
System.out.println("Enter your choice: ");
int choice = sc.nextInt();
sc.nextLine();
if ( choice == 1){
System.out.println("Enter the string to be encrypted : ");
char[] p = sc.next().toCharArray();
for ( int i = 0 ; i < p.length ; i++){
p[i] = Character.toUpperCase(p[i]);
}
System.out.println("Enter the value of a: ");
int a = sc.nextInt();
System.out.println("Enter the value of b: ");
int b = sc.nextInt();
char[] c = new char[p.length];
for (int i = 0 ; i < p.length ; i++){
c[i] = (char)((a*(p[i] -'A') + b)%26 + 'A');
}
System.out.println("The encrypted string is: ");
for (int i = 0 ; i < c.length ; i++){
System.out.print(c[i]);
}
System.out.println();
}else{
System.out.println("Enter the string to be decrypted: ");
char[] c = sc.next().toCharArray();
for ( int i = 0 ; i < c.length ; i++){
c[i] = Character.toUpperCase(c[i]);
}
System.out.println("Enter the value of a: ");
int a = sc.nextInt();
System.out.println("Enter the value of b: ");
int b = sc.nextInt();
char[] p = new char[c.length];
for (int i = 0 ; i < c.length ; i++){
p[i] = (char)((modInverse(a,26)*(c[i] -'A' - b + 26))%26 + 'A');
}
System.out.println("The decrypted string is: ");
for (int i = 0 ; i < p.length ; i++){
System.out.print(p[i]);
}
System.out.println();
}
sc.close();
}
}