凯撒密码的加密比较简单,其算法核心为将字母表中的字母移动一定的位置而实现加密。
其解密过程为加密的逆过程,为了简单描述凯撒密码的加密和解密过程,一下使用java对其过程进行模拟。考虑到字符的可读性,以下程序仅支持字母和数字,即只支持list集合中的字符。
package CaesarCode;
import java.util.ArrayList;
import java.util.Scanner;
public class CeasarCodePlus {
Scanner sc = new Scanner(System.in);
ArrayList list = new ArrayList();
void choose (){
// 初始化密码字符集合,如果你不想手动输入,只能提高时间复杂度喽
char element1 = '0';
for (int i = 0; i < 10; i++) {
list.add(element1);
element1 += 1;
}
for (int i = 'a'; i <= 'z'; i++) {
list.add((char)i);
}
for (int i = 'A'; i <= 'Z'; i++) {
list.add((char)i);
}
select:while (true){
System.out.println("****请选择您的操作****\n1.加密\n2.解密\n3.退出");
int choose = 0;
choose = sc.nextInt();
switch (choose){
case 1: encryption();
break;
case 2: decryption();
break;
case 3:
System.out.println("感谢使用本程序!");
return;
default: System.out.println("请输入正确的选择");
break;
}
}
}
// 加密函数
void encryption(){
String result = "";
System.out.print("请输入您要加密的字符串(仅限字母和数字):");
String str = sc.next();
System.out.print("请输入您要加密密钥(仅限数字):");
//将输入的密钥对集合长度取模,得到key
int key = sc.nextInt() % list.size();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int index = list.indexOf(c);
if(list.size() - list.indexOf(c) <= key){
index = list.indexOf(c) - list.size();
c = (char)list.get(index + key);
}else {
c = (char)list.get(index + key);
}
result += c;
}
System.out.println("加密后的密文为:" + result);
}
// 解密函数
void decryption(){
String result = "";
System.out.print("请输入你要解密的字符串(仅限字母和数字):");
String str = sc.next();
System.out.print("请输入解密的密钥(仅限数字):");
int key1 = sc.nextInt() % list.size();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int index = list.indexOf(c);
if(list.indexOf(c) < key1){
index = list.indexOf(c) + list.size();
c = (char)list.get(index - key1);
}else {
c = (char)list.get(index - key1);
}
result = result + c;
}
System.out.println("解密后的明文为:" + result);
}
public static void main(String[] args) {
CeasarCodePlus code = new CeasarCodePlus();
code.choose();
}
}
如果有问题欢迎评论留言!