古典密码-置换算法java实现

 最近阅读学习了一下加密算法,对古典算法中的置换算法进行了实现。原理我就不多说了,我们来看看加密解密的过程。

首先使用了如下的秘钥进行交换。

【交换秘钥】[3, 1, 7, 0, 2, 9, 4, 8, 5, 6]
【逆向交换秘钥】[3, 1, 4, 0, 6, 8, 9, 2, 7, 5]

【混淆后的内容】cveac11vdsgdhello world 

开始加密,补全矩阵中缺省的内容,
古典密码-置换算法java实现_第1张图片

【加密结果】ae vdlv tcgrehdso8cledwt1lt1op

进行解密
古典密码-置换算法java实现_第2张图片
【解密】混淆的字符串: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

 

你可能感兴趣的:(算法,古典密码,置换算法)