凯撒密码是一种替换加密的技术,明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文。例如,当偏移量是3的时候,所有的字母A将被替换成D,B变成E
import java.util.Scanner;
public class kaisa
{
private int key;
private Scanner scan;
public void jiami()
{
System.out.print("Please enter the key: ");
scan = new Scanner(System.in);//接收键盘数据
int key = scan.nextInt();//接收整数
System.out.print("Please enter the plaintext: ");
Scanner scan = new Scanner(System.in);
String pt = scan.nextLine();//接收明文
scan.close();
System.out.print("The passtext is: ");
char[] c = new char[pt.length()];//创建明文长度的数组
for(int i = 0; i < pt.length(); i++)
{
c[i] = pt.charAt(i);
if(c[i] >= 97 && c[i] <= 122)//针对小写字母
{
c[i] += key;
if(c[i] > 122)
c[i] -= 26;//小写字母的ascii大于122时则减去26,使其重新进入字母表中循环
}
else{
if(c[i]>=65&&c[i]<=90){//针对大写字母
c[i]+=key;
if(c[i]>90){
c[i]-=26;
}
}
}
System.out.print(c[i]);
}
}
public static void main(String[] args)
{
kaisa c = new kaisa();
c.jiami();
}
}
运行结果:
Please enter the key: 6
Please enter the plaintext: Hello World!
The passtext is: Nkrru Cuxrj!