-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVigenereCipher.java
45 lines (34 loc) · 1.09 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
import java.util.Scanner;
/**
* Created by Ruby on 3/20/2016.
*/
public class VigenereCipher {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.print("Enter key: ");
String key=in.nextLine();
System.out.print("Enter message: ");
String msg=in.nextLine();
System.out.print("The encrypted text: " + encrypt(msg, key));
}
static String encrypt(String msg, String key){
String encrypted="";
String alphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int val=0;
msg=msg.toUpperCase();
key=key.replaceAll(" ","").toUpperCase();
for (int i=0; i<msg.length(); i++){
if (msg.charAt(i)!=' '){
int index=(alphabets.indexOf(msg.charAt(i))+alphabets.indexOf(key.charAt(val)))%26;
encrypted+=alphabets.charAt(index);
if (val==key.length()-1)
val=0;
else
val++;
}else{
encrypted+='#';
}
}
return encrypted;
}
}