88
99public class Vigenere {
1010
11- public static String encrypt (final String message , final String key )
11+ public static String encrypt (final String message , final String key )
1212 {
1313
1414 String result = "" ;
1515
16- for (int i = 0 , j = 0 ; i < message .length (); i ++)
17- {
16+ for (int i = 0 , j = 0 ; i < message .length (); i ++) {
1817 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 ();
18+ if (Character .isLetter (c )){
19+ if (Character .isUpperCase (c )) {
20+ result += (char ) ((c + key .toUpperCase ().charAt (j ) - 2 * 'A' ) % 26 + 'A' );
21+
22+ } else {
23+ result += (char ) ((c + key .toLowerCase ().charAt (j ) - 2 * 'a' ) % 26 + 'a' );
24+
25+ }
2526 } else {
2627 result +=c ;
27- continue ;
2828 }
29+ j = ++j % key .length ();
2930 }
3031 return result ;
3132 }
3233
33- public static String decrypt ( final String message , final String key )
34+ public static String decrypt ( final String message , final String key )
3435 {
3536 String result ="" ;
3637
3738 for (int i = 0 , j = 0 ; i < message .length (); i ++){
3839
3940 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 {
41+ if (Character .isLetter (c )){
42+ if (Character .isUpperCase (c )) {
43+ result += ((char )('Z' -(25 -(c -key .toUpperCase ().charAt (j )))%26 ));
44+
45+ } else {
46+ result += ((char )('z' -(25 -(c -key .toLowerCase ().charAt (j )))%26 ));
47+
48+ }
49+ } else {
4750 result +=c ;
48- continue ;
4951 }
52+
5053 j = ++j % key .length ();
54+
5155 }
5256 return result ;
53- }
57+ }
5458 public static void main (String [] args ){
5559 String text ="Hello World!" ;
5660 String key ="itsakey" ;
@@ -60,4 +64,4 @@ public static void main (String [] args){
6064 System .out .println (decrypt (ciphertext , key ));
6165
6266 }
63- }
67+ }
0 commit comments