import java.util.Scanner;
/**
* java实现凯撒密码简单破解
* 密码:凯撒密码
* 凯撒(Caesar)密码是一种基于字符替换的对称式加密方法,它是通过对26个英文字母循环移位和替换来进行编码的。设待加密的消息为"Alibaba Group",加密后的密文是"RCzsrsr XIFLG",则采用的密匙k是____。
*/
public class TestCaesar {
public static void main(String[] args) {
System.out.println("凯撒密码破解法");
String text="baba";
String miwen="RCzsrsr XIFLG";
for(int key=0;key<64;key++)
{
String data=Decrypt(miwen, key);
if(data.indexOf(text)!=-1)
{
System.out.println("key="+key);
System.out.println(data);
break;
}
}
System.out.println("finish");
}
public static void main2(String[] args) {
System.out.println("[A 加密][J 解密],Please Choose One");
Scanner c = new Scanner(System.in);// 创建Scanner键盘输入对象
String s1 = c.nextLine();// 获取本行的字符串
if (s1.equalsIgnoreCase("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类型
String string=Encryption(s, key);
System.out.println(s + " 加密后为: " + string);
} else if (s1.equalsIgnoreCase("J")) {
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类型
String string=Decrypt(s, key);// 調用解密方法
System.out.println(s + " 加密后为: " + string);
}
}
public static String Encryption(String str, int k) {// 加密
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 Decrypt(String str, int n) {// 解密
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;
}
}
java实现凯撒密码简单破解
最新推荐文章于 2024-08-06 18:58:18 发布