-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVigenereCipher.java
88 lines (71 loc) · 2.23 KB
/
VigenereCipher.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
public class VigenereCipher {
static char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
/* Sifrelenecek mesajin ve anahtar kelimenin index degerleri toplanir.
* Toplama islemi sirasinda elde edilen sonuclarin alfabe sayisindan buyuk olma ihtimaline karsi mod alma islemi uygulanir.
*/
public static String encryption(String plainText,String key)
{
StringBuilder cipherText = new StringBuilder();
plainText=plainText.toLowerCase();
int count=0;
for(char q:plainText.toCharArray())
{
if(!Character.isLetter(q))
{
cipherText.append(q);
continue;
}
count=count==key.length() ? 0:count;
int now = getIndex(q);
int shift = getIndex(key.charAt(count));
int target = (now+shift) % alphabet.length;
cipherText.append(alphabet[target]);
count++;
}
return cipherText.toString();
}
/* Sifreli mesajin index degerinden anahtar kelimenin index degeri cikarilir.
* Cikarma islemi sirasinda elde edilen sonuclar arasinda 0'dan kucuk olan degerlerin uzerine mod alma isleminde kullanilan sayi degeri eklenir.
*/
public static String decryption(String cipherText,String key)
{
StringBuilder plainText = new StringBuilder();
int count=0;
for(char q:cipherText.toCharArray())
{
if(!Character.isLetter(q))
{
plainText.append(q);
continue;
}
count=count==key.length() ? 0:count;
int now = getIndex(q);
int shift = getIndex(key.charAt(count));
int target = (now-shift) % alphabet.length;
target = target<0 ? alphabet.length + target : target;
plainText.append(alphabet[target]);
count++;
}
return plainText.toString();
}
/*
* Alfabe dizisindeki aranan karakterin indexini donduren metod.
*/
public static int getIndex(char q)
{
for(int i=0;i<alphabet.length;i++)
{
if(alphabet[i]==q) return i;
}
return 0;
}
public static void main(String[] args) {
String plainText = "kirklareli universitesi yazilim muhendisligi";
String key ="klu";
System.out.println("Metnin Acik Hali :"+plainText);
String cipherText = encryption(plainText,key);
System.out.println("Metnin Sifrelenmis Hali :"+cipherText);
plainText = decryption(cipherText,key);
System.out.println("Sifreli Metnin Cozulmus Hali :"+plainText);
}
}