1+ package ciphers ;
2+
3+ /**
4+ * A Java implementation of Vigenere Cipher.
5+ * @author straiffix
6+ */
7+
8+
9+ public class Vigenere {
10+
11+ public static String encrypt (final String message , final String key )
12+ {
13+
14+ String result = "" ;
15+
16+ for (int i = 0 , j = 0 ; i < message .length (); i ++)
17+ {
18+ char c = message .charAt (i );
19+ if (c >= 'A' && c <= 'Z' ) {
20+ result += (char ) ((c + key .toUpperCase ().charAt (j ) - 2 * 'A' ) % 26 + 'A' );
21+ j = ++j % key .length ();
22+ } else if (c >= 'a' && c <= 'z' ) {
23+ result += (char ) ((c + key .toLowerCase ().charAt (j ) - 2 * 'a' ) % 26 + 'a' );
24+ j = ++j % key .length ();
25+ } else {
26+ result +=c ;
27+ continue ;
28+ }
29+ }
30+ return result ;
31+ }
32+
33+ public static String decrypt ( final String message , final String key )
34+ {
35+ String result ="" ;
36+
37+ for (int i = 0 , j = 0 ; i < message .length (); i ++){
38+
39+ char c = message .charAt (i );
40+ if ((c >= 'A' && c <= 'Z' )){
41+ result += ((char )('Z' -(25 -(c -key .toUpperCase ().charAt (j )))%26 ));
42+ }
43+ else if (c >= 'a' && c <= 'z' ){
44+ result += ((char )('z' -(25 -(c -key .toLowerCase ().charAt (j )))%26 ));
45+ }
46+ else {
47+ result +=c ;
48+ continue ;
49+ }
50+ j = ++j % key .length ();
51+ }
52+ return result ;
53+ }
54+ public static void main (String [] args ){
55+ String text ="Hello World!" ;
56+ String key ="itsakey" ;
57+ System .out .println (text );
58+ String ciphertext =encrypt (text , key );
59+ System .out .println (ciphertext );
60+ System .out .println (decrypt (ciphertext , key ));
61+
62+ }
63+ }
0 commit comments