凯撒密码(移位密码)
移位密码是一种古典密码,实际上是替换密码的一个特例,它有很严格的数学定义
// 移位密码
import java.util.Scanner;
public class Caesar {
public static void main(String[] args) {
System.out.println("[1 加密][2 解密],请选择一个");
Scanner c = new Scanner(System.in);// 创建Scanner对象
String s1 = c.nextLine();// 获取本行的字符串
if (s1.equalsIgnoreCase("1")) {
// 判断变量s1与A是否相等,忽略大小
System.out.println("请输入明文:");
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println("请输入密钥:");
Scanner sc1 = new Scanner(System.in);
int key = sc1.nextInt();// 将下一输入项转换成int类型
System.out.println(Encryption(s, key));// 调用Encryption方法
} else if (s1.equalsIgnoreCase("2")) {
System.out.println("请输入密文:");
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println("请输入密钥:");
Scanner sc1 = new Scanner(System.in);
int key = sc1.nextInt();
System.out.println(Decrypt(s, key)); // 调用Encryption方法
}
}
public static String Decrypt(String str, int n) {
// TODO Auto-generated method stub
// 解密
int k = Integer.parseInt("-" + n);
String string = "";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= 'a' && c <= 'z')// 如果字符串中的某个字符是小写字母
{
c += k % 26;// 移动key%26位
if (c < 'a')
c += 26;// 向左超界
if (c > 'z')
c -= 26;// 向右超界
} else if (c >= 'A' && c <= 'Z')// 如果字符串中的某个字符是大写字母
{
c += k % 26;// 移动key%26位
if (c < 'A')
c += 26;// 向左超界
if (c > 'Z')
c -= 26;// 向右超界
}
string += c;// 将解密后的字符连成字符串
}
return string;
}
public static String Encryption(String str, int k) {
// TODO Auto-generated method stub
// 加密
String string = "";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= 'a' && c <= 'z')// 如果字符串中的某个字符是小写字母
{
c += k % 26;// 移动key%26位
if (c < 'a')
c += 26;// 向左超界
if (c > 'z')
c -= 26;// 向右超界
} else if (c >= 'A' && c <= 'Z')// 如果字符串中的某个字符是大写字母
{
c += k % 26;// 移动key%26位
if (c < 'A')
c += 26;// 向左超界
if (c > 'Z')
c -= 26;// 向右超界
}
string += c;// 将解密后的字符连成字符串
}
return string;
}
}