-
Notifications
You must be signed in to change notification settings - Fork 0
/
MultiplicativeCipher.java
79 lines (63 loc) · 1.89 KB
/
MultiplicativeCipher.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
public class MultiplicativeCipher
{
static char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
public static String encryption(String plainText,int shift)
{
assert(shift>= -(alphabet.length) && shift<=alphabet.length);
plainText = plainText.trim();
plainText=plainText.toLowerCase();
if(shift<0) shift=alphabet.length+shift;
StringBuilder cipherText=new StringBuilder();
for(char q:plainText.toString().toCharArray())
{
if(!Character.isLetter(q))
{
cipherText.append(q);
continue;
}
int index = ( getIndex(q) * shift ) % alphabet.length ;
cipherText.append(alphabet[index]);
}
return cipherText.toString();
}
public static String decryption(String cipherText,int shift)
{
cipherText = cipherText.trim();
StringBuilder plainText = new StringBuilder();
int j=0;
for(char q:cipherText.toString().toCharArray())
{
if(!Character.isLetter(q))
{
plainText.append(q);
continue;
}
int index = getIndex(q);
for(int i=0;i<alphabet.length;i++)
{
if( ((i * shift) - index) % alphabet.length == 0 )
plainText.append(alphabet[i]);
}
}
return plainText.toString();
}
public static int getIndex(Character ch)
{
for(int i=0;i<alphabet.length;i++)
{
if(alphabet[i] == ch)
return (i);
}
return 0;
}
public static void main(String args[])
{
int shift = 5;
String plainText = "can you hear me?";
System.out.println("Metnin Acik Hali : "+ plainText);
String cipherText = encryption(plainText,shift);
System.out.println("Metnin Sifrelenmis Hali : "+ cipherText);
String decryptedText = decryption(cipherText,shift);
System.out.println("Metnin Acik Hali : "+ decryptedText);
}
}