古典恺撒移位密码破解

1. cipher text

bmjs dtz uqfd ymj lfrj tk ymwtsjx dtz bns tw dtz inj ymjwj nx st rniiqj lwtzsi

刚看到需要解密的文本,就觉得它很像移位密码,于是开始试了一下。
源代码:
求最大公因数:Arithmetic.java

public class Arithmetic {
    
    
    int x = 0;
    int y = 0;

    public int euclid(int a,int b){
    
    
        int first,second;
        first = a;
        second = b;
        int temp;
        if(first<second){
    
    
            temp = first;
            first = second;
            second = temp;
        }
        while(first%second!=0){
    
    
            temp = first%second;
            first = second;
            second = temp;
        }
        return second;
    }
}

移位密码的解密:Affine.java

class Affine {
    
    
        String deciphering(String s, int a, int b){
    
    // 解密的实现
            char[] ch = s.toCharArray();
            int length = ch.length;// 密文长度
            int[] in = new int[length];
            for (int i = 0; i < ch.length; i++) {
    
    
                if(ch[i] == ' '){
    
      //如果是空格就不用解密,直接跳过
                }
                else {
    
    
                    in[i] = ch[i] - 97;// 利用ascii变成0-25数字
                    in[i] = ((in[i] - b) * a) % 26;  // 解密
                    if (in[i] < 0) {
    
    
                        in[i] += 26;
                    }
                    ch[i] = (char) (in[i] + 97);// 将数字变成字母
                }
            }
            return String.valueOf(ch);// 将字符串数字变成String类型的字符串,返回
        }
}

主类:Test.java

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Arithmetic arithmetic = new Arithmetic();
        final int MOD = 26;
        int [] gcd = new int[12];
        int m = 0;
        String out = null;
        for(int i=1;i<MOD;i++){
    
    
            if((arithmetic.euclid(i,MOD)) == 1) {
    
       //求与26互素的数
                gcd[m] = (arithmetic.euclid_2(i,MOD)+26)%26; //求这些数mod26的逆,并把它加入gcd数组
                m++;
            }
        }
        Scanner input = new Scanner(System.in);
        System.out.println("请输入需要解密的密文:");
        String s = input.nextLine();// 输入密文
        Affine affine = new Affine();
        int k =1;
        for(int i=0;i<12;i++) {
    
    
            for (int j = 0; j < 26; j++) {
    
    
                out = affine.deciphering(s, gcd[i], j);
                System.out.println("第"+k+"条明文为:"+out);
                k++;
            }
        }
    }
}

实验结果截图:
在这里插入图片描述

最后成功破解了由仿射密码加密的密文,得到了明文when you play the game of thrones you win or you die there is no middle ground。

猜你喜欢

转载自blog.csdn.net/Onlyone_1314/article/details/108908660
今日推荐