古典密碼-置換算法java實現

 最近閱讀學習了一下加密算法,對古典算法中的置換算法進行了實現。原理我就不多說了,我們來看看加密解密的過程。

首先使用瞭如下的祕鑰進行交換。

【交換祕鑰】[3, 1, 7, 0, 2, 9, 4, 8, 5, 6]
【逆向交換祕鑰】[3, 1, 4, 0, 6, 8, 9, 2, 7, 5]

【混淆後的內容】cveac11vdsgdhello world 

開始加密,補全矩陣中缺省的內容,

【加密結果】ae vdlv tcgrehdso8cledwt1lt1op

進行解密

【解密】混淆的字符串:cveac11vdsgdhello world etptt8

代碼如下

import java.util.Arrays;

/*
 * 古典密碼算法之  置換算法
 * @author mtngt11
 */
public class ClassicalCryptography {

    private final static String key = "3170294856";
    private final static String key2 = "vdsgd";
    private final static int head_len = 30;
    public static void main(String[] args) {


        String content = "hello world";
        String head = randomString(head_len);
        String end = randomString(50+(int)(Math.random()*30));
        //在頭尾加入混淆的字符串,
        content = head + content.length()+ key2 +content + end;
        System.out.println("【混淆後的內容】"+content);
        String encryptResult = null;
        int[] keyArr = new int[key.length()];
        int[] keyArr_reversed = new int[key.length()];
        for (int i = 0; i < key.length(); i++) {
            int a = Integer.parseInt(key.substring(i, i + 1));
            keyArr[i] = a;
            keyArr_reversed[a] = i;
        }
        System.out.println("【交換祕鑰】"+Arrays.toString(keyArr));
        System.out.println("【逆向交換祕鑰】"+Arrays.toString(keyArr_reversed));
        System.out.println(Arrays.toString(keyArr_reversed));
        try {
            encryptResult = encrypt(content,keyArr);
            System.out.println("【加密結果】"+encryptResult);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            String decryptResult = decrypt(encryptResult,keyArr_reversed,head_len);
            System.out.println("【解密結果】"+decryptResult);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static String randomString(int len) {
        // TODO Auto-generated method stub
        String[] strs = new String[] {"a","b","c","d","e","f","g","h","i"
                ,"j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"," "," "," "," "," "};
        StringBuilder sb = new StringBuilder();


        for(int i=0;i<len;i++) {
            int ran = (int)(Math.random()*strs.length);
            sb.append(strs[ran]);
        }

        return sb.toString();
    }

    public static String encrypt(String initCode,int[] arr)throws Exception{

        StringBuilder sb = new StringBuilder();
        int len = key.length();
        int codeLength = initCode.length();
        int rows = (int)Math.ceil(codeLength/(double)len );
        //轉換爲矩陣
        char[][] initChar = new char[rows][len];
        for(int i = 0; i < initChar.length; i++ ) {
            for (int j = 0; j < initChar[0].length; j++) {
                try {
                    initChar[i][j] = initCode.charAt((i) * initChar[0].length + j);
                } catch (Exception e) {
                    //多出來的用@表示
//	            	 initChar[i][j] = '#';
                    initChar[i][j] = randomString(1).toCharArray()[0];
                }
            }
        }

        char[][] targetChar = new char[rows][key.length()];
        //按祕鑰交換
        for(int j = 0; j < targetChar[0].length; j++ ) {
            for (int i = 0; i < targetChar.length; i++) {
                targetChar[i][j] = initChar[i][arr[j]];
                sb.append(initChar[i][arr[j]]);
            }
        }

        System.out.println("【加密】交換前的矩陣");
        printMatrix(initChar);
        System.out.println("【加密】交換後的矩陣");
        printMatrix(targetChar);
        System.out.println();
        return sb.toString();
    }

    public static String decrypt(String targetCode, int[] arr,int head_len)throws Exception {
        StringBuilder sb = new StringBuilder();
        int codeLength = targetCode.length();
        int rows = (int) Math.ceil(codeLength / (double) key.length());
        char[][] targetChar = new char[rows][key.length()];
        //轉換爲矩陣
        for(int j = 0; j < targetChar[0].length; j++ ) {
            for (int i = 0; i < targetChar.length; i++) {
                targetChar[i][j] = targetCode.charAt(
                        (j) * targetChar.length + i
                );
            }
        }
        System.out.println("【解密】交換前矩陣");
        printMatrix(targetChar);

        char[][] initChar = new char[rows][key.length()];


        //按祕鑰交換
        for (int i = 0; i < targetChar.length; i++) {
            for(int j = 0; j < targetChar[0].length; j++ ) {
                sb.append(targetChar[i][arr[j]]);
            }
        }

        System.out.println("【解密】混淆的字符串:"+sb.toString());
        String res = sb.toString();
        // 解密。去除混淆字符串
        if(sb.toString().contains(key2)) {
            String partA = res.substring(0, sb.toString().indexOf(key2));
//            System.out.println(partA);
            String len = partA.substring(head_len,sb.toString().indexOf(key2));
//            System.out.println("len:"+len);
            String partB = res.substring(sb.toString().indexOf(key2)+ key2.length());
//            System.out.println("b:"+partB);
            res = partB.substring(0,Integer.parseInt(len));
//            System.out.println("res"+res);
        }
        return res;
    }
    private static void printMatrix(char[][] charMatrix){
        System.out.println("-------------------");
        for (int i = 0; i < charMatrix.length; i++) {
            for (int j = 0; j < charMatrix[0].length; j++) {
                System.out.print(charMatrix[i][j]+" ");
            }
            System.out.println();
        }
        System.out.println("-------------------");
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章