2024-07-14  2024-07-14    4548 字  10 分钟

AES加密

DES加密的过程

具体的原理可以参考:

DES实现

文章给出了AES加密算法的一个实现。未做任何优化,仅供学习参考,计算速度跟专业的库相比应该有很大差距。虽然密码学算法是安全的,但是工程实现中可能存在其他攻击,没有足够的信心,不要使用自己写的加密算法做加密。

import java.math.BigInteger;
import java.util.Random;

/**
 * @author miracle
 * @date 2022/11/14 22:12
 * @description: <br/>
 */
public class Main {

    /**
     * 将一个十进制的数字转化为指定进制,指定位数的数字符串(位数不够,前面补零)
     * 如:
     * -	将 33 转化为长度为 8 的二进制字符串
     * -		则结果为: "00100001"
     *
     * @param number 带转换的十进制数字
     * @param radix  将要转化为的进制数
     * @param length 转化后字符串的长度
     * @return 满足要求的字符串
     */
    public static String toString(int number, int radix, int length) {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int bit = number % radix;
            str.insert(0, bit);
            number = number / radix;
        }
        return str.toString();
    }

    // --------------------------------------------------- 常量定义 -------------------------------------------------------------------

    // S盒
    private static int[][] SBox = new int[][]{
            {0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76},//
            {0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0},//
            {0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15},//
            {0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75},//
            {0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84},//
            {0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF},//
            {0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8},//
            {0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2},//
            {0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73},//
            {0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB},//
            {0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79},//
            {0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08},//
            {0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A},//
            {0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E},//
            {0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF},//
            {0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16}
    };

    // 列混合左乘的矩阵
    private static int[][] mixCol = {
            {2, 3, 1, 1},//
            {1, 2, 3, 1},//
            {1, 1, 2, 3},//
            {3, 1, 1, 2}
    };

    // 密钥扩展算法中的轮常量
    private static int[][] RC = new int[][]{
            {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36},//
            {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},//
            {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},//
            {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
    };

    private static int[][] InvMixCol = {
            {0x0e, 0x0b, 0x0d, 0x09},//
            {0x09, 0x0e, 0x0b, 0x0d},//
            {0x0d, 0x09, 0x0e, 0x0b},//
            {0x0b, 0x0d, 0x09, 0x0e}
    };

    // 逆 S 盒
    private static int[][] InvSBox = new int[][]{
            {0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb},//
            {0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb},//
            {0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e},//
            {0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25},//
            {0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92},//
            {0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84},//
            {0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06},//
            {0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b},//
            {0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73},//
            {0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e},//
            {0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b},//
            {0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4},//
            {0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f},//
            {0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef},//
            {0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61},//
            {0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d}
    };

    // --------------------------------------------------- 工具函数 -------------------------------------------------------------------
    // 工具函数,将int类型的二维数组以十六进制显示,用来查看数据的正确性
    private static void showByHex(int[][] a) {
        int i = 0;
        System.out.println("[");
        for (int[] rows : a) {
            i = 0;
            System.out.print("[");
            for (int row : rows) {
                if (i < 4) {
                    String toHexString = Integer.toHexString(row);
                    if (toHexString.length() == 1) {
                        toHexString = "0" + toHexString;
                    }
                    System.out.print(toHexString + ",");
                    i++;
                } else {
                    i = 0;
                    String toHexString = Integer.toHexString(row);
                    if (toHexString.length() == 1) {
                        toHexString = "0" + toHexString;
                    }
                    System.out.print(toHexString + ",");
                    i++;
                }
            }
            System.out.println("]");
        }
        System.out.println("]");
    }
    // --------------------------------------------------- 加密算法 -------------------------------------------------------------------
    // ------------------------------ 格式化工具 ----------------------------------

    /**
     * 将给定二进制明文转换为4*4的矩阵,矩阵中的元素按照列优先的顺序排列
     *
     * @param plaintext 长度位128bit的明文数据,或者密钥数据
     * @return 将128bit的数据平均分成16份,按照列优先的顺序存储到一个4*4的矩阵中返回。
     */
    private static int[][] getMatrix(String plaintext) {
        int[][] res = new int[4][4];
        for (int i = 0; i < plaintext.length(); ) {
            StringBuilder bytes = new StringBuilder();
            for (int j = 0; j < 8; j++) {
                bytes.append(plaintext.charAt(i++));
            }
            int row = ((i - 1) / 8) % 4;
            int col = ((i - 1) / 32) % 4;
            res[row][col] = Integer.parseInt(bytes.toString(), 2);
        }
        return res;
    }

    /**
     * 将明文转化的矩阵还原为明文,是getMatrix()函数的逆过程
     *
     * @param matrix 明文转化的矩阵
     * @return 还原的矩阵
     */
    private static String matrixToString(int[][] matrix) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                builder.append(toString(matrix[j][i], 2, 8));
            }
        }
        return builder.toString();
    }
    // ------------------------------ 主要加密过程 ----------------------------------

    /**
     * 初始变换
     * 将明文对应的矩阵和密钥转化的矩阵取异或(混淆)
     *
     * @return 返回异或的结果
     */
    private static int[][] InitialRound(String plaintext, String key) {
        int[][] res = new int[4][4];
        // 将明文和密钥化为矩阵
        int[][] p = getMatrix(plaintext);
        int[][] k = getMatrix(key);
        // 将明文矩阵和密钥矩阵按列异或
        res = xor(p, k);
        return res;
    }

    // 按列异或
    private static int[][] xor(int[][] a, int[][] b) {
        int[][] res = new int[4][4];
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                res[j][i] = a[j][i] ^ b[j][i];
            }
        }
        return res;
    }

    /**
     * 前九轮加密
     * 加密算法的核心,每次需要四个步骤
     * 1. 字节代换
     * 2. 行移位
     * 3. 列混合
     * 4. 轮密钥加
     *
     * @param initialRound 明文经过初始变换后的到的密文
     * @param subKeys      一个密钥和十个子密钥
     * @return 明文九轮变换后的密文
     */
    private static int[][] FirstNineRounds(int[][] initialRound, int[][][] subKeys) {
        //
        for (int i = 1; i <= 9; i++) {
            int[][] subBytes = SubBytes(initialRound);
            int[][] shiftRows = ShiftRows(subBytes);
            int[][] mixColumns = MixColumns(shiftRows);
            initialRound = AddRoundKey(mixColumns, subKeys[i]);
        }
        return initialRound;
    }

    /**
     * 最后一轮加密
     * 与前九轮加密相比,少了列混合这一步
     *
     * @param initialRound 明文经过初始变换后的到的密文
     * @param subKeys      一个密钥和十个子密钥
     * @return 第十轮加密后的密文,即最终密文
     */
    private static int[][] LastRound(int[][] initialRound, int[][][] subKeys) {
        int[][] subBytes = SubBytes(initialRound);
        int[][] shiftRows = ShiftRows(subBytes);
        initialRound = AddRoundKey(shiftRows, subKeys[10]);
        return initialRound;
    }
    // ------------------------------ 十轮加密的细节 ----------------------------------

    /**
     * 字节代换
     * 由于明文矩阵中每个元素由2个十六进制的数字表示,以高位上的十六进制数字位行号,低位上的十六进制数字位列号,查询S盒
     * 将S盒中对应位置的元素作为 字节代换后的元素。将整个矩阵都进行该代换即可得到字节代换后的密文矩阵
     *
     * @param initialRound 待加密矩阵
     * @return 待加密矩阵经过字节代换后得到的矩阵
     */
    private static int[][] SubBytes(int[][] initialRound) {
        int[][] res = new int[4][4];
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                // 获取 行列索引
                int row = initialRound[j][i] >>> 4 & 0b1111;
                int col = initialRound[j][i] & 0b1111;
                res[j][i] = SBox[row][col];
            }
        }
        return res;
    }

    /**
     * 行移位
     * 对于字节代换后的矩阵,将其第i行的元素循环左移i位(i = 0,1,2,3)
     *
     * @return 移位后的矩阵
     */
    private static int[][] ShiftRows(int[][] subBytes) {
        for (int i = 1; i < 4; i++) {
            subBytes[i] = leftMove(subBytes[i], i);
        }
        return subBytes;
    }

    // 反转指定位置的字符串
    private static int[] reverseStr(int[] arr, int start, int end) {
        while (start < end) {
            int temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            start++;
            end--;
        }
        return arr;
    }

    // 将字符串向左循环移动 n 位
    private static int[] leftMove(int[] arr, int n) {
        arr = reverseStr(arr, 0, n - 1);
        arr = reverseStr(arr, n, arr.length - 1);
        return reverseStr(arr, 0, arr.length - 1);
    }

    /**
     * 列混合
     * 将行移位后的矩阵左乘一个给定的矩阵 mixCol 这里的乘法是定义在 优先于GF(2^8)上的乘法
     *
     * @param ShiftRows 行移位后的矩阵
     * @return 列混合后的矩阵
     */
    private static int[][] MixColumns(int[][] ShiftRows) {
        int[][] res = new int[4][4];
        int i, j, k;
        for (i = 0; i < 4; i++) {
            for (j = 0; j < 4; j++) {
                for (k = 0; k < 4; k++) {
                    res[i][j] ^= Multiple(mixCol[i][k], ShiftRows[k][j]);
                }
            }
        }
        return res;
    }

    // 有限域 GF(2^8) 上的乘法
    private static int Multiple(int a, int b) {
        int[] multiplier = new int[8];
        // 获取乘数
        multiplier[0] = a;
        int prior = a;
        for (int i = 1; i < 8; i++) {
            multiplier[i] = prior & 0b1111111;
            multiplier[i] <<= 1;
            if ((prior >>> 7 & 1) == 1) {
                multiplier[i] ^= 0b00011011;
            }
            prior = multiplier[i];
        }
        int res = 0;
        for (int i = 0; i < 8; i++) {
            if ((b & 1) == 1) {
                res = res ^ multiplier[i];
            }
            b >>>= 1;
        }
        return res;
    }

    /**
     * 轮密钥加
     * 将列混合后的矩阵与对应的子密钥按列进行异或
     *
     * @param mixColumns 列混合后的矩阵
     * @param subKey     本轮加密对应的子密钥
     * @return 轮密钥加后的矩阵
     */
    private static int[][] AddRoundKey(int[][] mixColumns, int[][] subKey) {
        int[][] res = new int[4][4];
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                res[i][j] = mixColumns[i][j] ^ subKey[i][j];
            }
        }
        return res;
    }
    // --------------------------------------------------- 密钥扩展算法  ---------------------------------------------------------------------

    /**
     * 密钥扩展算法
     * 通过给定的16个字节密钥,生成一个176字节的轮密钥,里面包括原密钥和其生成的十个子密钥(每个子密钥都是16个字节)
     *
     * @param key 密钥
     * @return 子密钥集合
     */
    private static int[][][] getSubKeys(int[][] key) {
        int[][][] subKeys = new int[11][4][4];
        // 分别获取十个子密钥
        int[][] W = new int[4][44];
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                W[i][j] = key[i][j];
            }
        }
        int round = 0;
        for (int i = 4; i < 44; i++) {
            if (i % 4 != 0) {
                for (int j = 0; j < 4; j++) {
                    W[j][i] = W[j][i - 4] ^ W[j][i - 1];
                }
            } else {
                int[] Wi = new int[]{W[0][i - 1], W[1][i - 1], W[2][i - 1], W[3][i - 1]};
                int[] T = T(Wi, round++);
                for (int j = 0; j < 4; j++) {
                    W[j][i] = W[j][i - 4] ^ T[j];
                }
            }
        }
        // 密钥何其生成的十个子密钥
        for (int k = 0; k < 11; k++) {
            for (int i = 0; i < 4; i++) {
                for (int j = k * 4; j < k * 4 + 4; j++) {
                    subKeys[k][i][j % 4] = W[i][j];
                }
            }
        }
        return subKeys;
    }

    /**
     * T函数
     * 当i是四的倍数时,用来处理W[i-1],以增加密码的安全性
     *
     * @param Wi    待处理的列向量,该向量的i是四的倍数
     * @param round AES一共要进行十轮的加密,round记录现在是第几轮加密(round从1开始)
     * @return 处理后的列向量
     */
    private static int[] T(int[] Wi, int round) {
        int[] wordCycle = wordCycle(Wi);
        int[] sBoxReplace = SBoxReplace(wordCycle);
        return roundConstantXOR(sBoxReplace, round);
    }

    // T函数 ----- 字循环
    private static int[] wordCycle(int[] Wi) {
        return leftMove(Wi, 1);
    }

    // T函数 ----- SBox代换
    private static int[] SBoxReplace(int[] wordCycle) {
        for (int i = 0; i < 4; i++) {
            // 获取 行列索引
            int row = wordCycle[i] >>> 4 & 0b1111;
            int col = wordCycle[i] & 0b1111;
            wordCycle[i] = SBox[row][col];
        }
        return wordCycle;
    }

    // T函数 ----- 轮常量异或
    private static int[] roundConstantXOR(int[] SBoxReplace, int round) {
        for (int i = 0; i < 4; i++) {
            SBoxReplace[i] ^= RC[i][round];
        }
        return SBoxReplace;
    }
    // --------------------------------------------------- 解密算法 -------------------------------------------------------------------

    private static int[][] InvInitialRound(String ciphertext, int[][] key) {
        int[][] res;
        // 将明文和密钥化为矩阵
        int[][] c = getMatrix(ciphertext);
        // 将明文矩阵和密钥矩阵按列异或
        res = xor(c, key);
        return res;
    }

    private static int[][] InvFirstNineRounds(int[][] initialRound, int[][][] subKeys) {
        //
        for (int i = 1; i <= 9; i++) {
            int[][] invShiftRows = InvShiftRows(initialRound);
            int[][] invSubBytes = InvSubBytes(invShiftRows);
            int[][] invAddRoundKey = InvAddRoundKey(invSubBytes, subKeys[10 - i]);
            initialRound = InvMixColumns(invAddRoundKey);
        }
        return initialRound;
    }

    private static int[][] InvShiftRows(int[][] initialRound) {
        for (int i = 1; i < 4; i++) {
            initialRound[i] = leftMove(initialRound[i], 4 - i);
        }
        return initialRound;
    }

    private static int[][] InvSubBytes(int[][] invShiftRows) {
        int[][] res = new int[4][4];
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                // 获取 行列索引
                int row = invShiftRows[j][i] >>> 4 & 0b1111;
                int col = invShiftRows[j][i] & 0b1111;
                res[j][i] = InvSBox[row][col];
            }
        }
        return res;
    }

    private static int[][] InvAddRoundKey(int[][] mixColumns, int[][] subKey) {
        int[][] res = new int[4][4];
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                res[i][j] = mixColumns[i][j] ^ subKey[i][j];
            }
        }
        return res;
    }

    private static int[][] InvMixColumns(int[][] invAddRoundKey) {
        int[][] res = new int[4][4];
        int i, j, k;
        for (i = 0; i < 4; i++) {
            for (j = 0; j < 4; j++) {
                for (k = 0; k < 4; k++) {
                    res[i][j] ^= Multiple(InvMixCol[i][k], invAddRoundKey[k][j]);
                }
            }
        }
        return res;
    }

    private static int[][] InvLastRound(int[][] initialRound, int[][][] subKeys) {
        int[][] invShiftRows = InvShiftRows(initialRound);
        int[][] invSubBytes = InvSubBytes(invShiftRows);
        initialRound = InvAddRoundKey(invSubBytes, subKeys[0]);
        return initialRound;
    }
    // --------------------------------------------------- 128bit加密解密 -------------------------------------------------------------------

    /**
     * 加密核心算法(一次加密128bit数据)
     *
     * @param plaintext 明文转化的二进制组成的字符串。
     * @param key       密钥转化的以二进制表示的字符串
     * @return 128bit明文加密得到的密文
     */
    private static String encryptCore(String plaintext, String key) {
        // 1. 初始变换
        int[][] initialRound = InitialRound(plaintext, key);
        // 2. 获取子密钥
        int[][][] subKeys = getSubKeys(getMatrix(key));
        // 3. 前九轮变换
        int[][] firstNineRounds = FirstNineRounds(initialRound, subKeys);
        // 4. 第十轮变换
        int[][] lastRound = LastRound(firstNineRounds, subKeys);
        // 5. 将密文矩阵转为加密后的二进制字符串返回
        return matrixToString(lastRound);
    }

    /**
     * 解密核心算法(一次解密128bit)
     *
     * @param ciphertext 密文
     * @return 加密后的明文
     */
    private static String decryptCore(String ciphertext, String key) {
        // 1. 获取密钥
        int[][][] subKeys = getSubKeys(getMatrix(key));
        // 2. 轮密钥加
        int[][] invInitialRound = InvInitialRound(ciphertext, subKeys[10]);
        // 3. 逆九轮循环
        int[][] invFirstNineRounds = InvFirstNineRounds(invInitialRound, subKeys);
        // 4. 逆最后一轮
        int[][] invLastRound = InvLastRound(invFirstNineRounds, subKeys);
        // 5. 将密文转化为明文字符串
        return matrixToString(invLastRound);
    }
    // --------------------------------------------------- 任意字符串加密解密 -------------------------------------------------------------------

    /**
     * 加密任意长度的字符串
     *
     * @param plaintext 明文,可以是任意字符串
     * @param key       密钥,128bit的二进制组成的字符串
     * @return plaintext经过密钥key加密后的密文
     */
    private static String encrypt(String plaintext, String key) {
        byte[] bytes = plaintext.getBytes();
        int remainder = bytes.length % 16;
        StringBuilder res = new StringBuilder();
        if (remainder != 0) {
            // 先将前面被十六整除的字节加密
            for (int i = 0; i < bytes.length - remainder; ) {
                StringBuilder p = new StringBuilder();
                for (int j = 0; j < 16; j++) {
                    p.append(toString(bytes[i++], 2, 8));
                }
                String c = encryptCore(p.toString(), key);
                res.append(c);
            }
            // 剩下的字节不够16个,用 "$" 即 36 填充到 16 个,并加密
            StringBuilder temp = new StringBuilder();
            for (int i = bytes.length - remainder; i < bytes.length; i++) {
                temp.append(toString(bytes[i], 2, 8));
            }
            for (int i = 0; i < 16 - remainder; i++) {
                temp.append(toString(36, 2, 8));
            }
            String c = encryptCore(temp.toString(), key);
            res.append(c);
        } else {
            for (int i = 0; i < bytes.length; ) {
                StringBuilder p = new StringBuilder();
                for (int j = 0; j < 16; j++) {
                    p.append(toString(bytes[i++], 2, 8));
                }
                String c = encryptCore(p.toString(), key);
                res.append(c);
            }
        }
        return res.toString();
    }

    /**
     * 解密密文,将其恢复为明文
     *
     * @param ciphertext 密文
     * @param key        密钥
     * @return 明文
     */
    private static String decrypt(String ciphertext, String key) {
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < ciphertext.length(); ) {
            StringBuilder c = new StringBuilder();
            for (int j = 0; j < 128; j++) {
                c.append(ciphertext.charAt(i++));
            }
            String p = decryptCore(c.toString(), key);
            String string = binaryToString(p);
            res.append(string);
        }
        return res.toString();
    }

    /**
     * 佛南工具函数,将二进制数字转化为字符串
     *
     * @param binary 用字符串转化的二进制
     * @return 二进制转换为的字符串
     */
    private static String binaryToString(String binary) {
        int i = 0;
        int len = binary.length();
        byte[] bytes = new byte[16];
        int idx = 0;
        while (i < len) {
            StringBuilder builder = new StringBuilder();
            boolean isPositve = true;
            isPositve = binary.charAt(i++) == 1 ? false : true;
            for (int j = 0; j < 7; j++) {
                builder.append(binary.charAt(i++));
            }
            if (isPositve) {
                bytes[idx++] = Byte.parseByte(builder.toString(), 2);
            } else {
                bytes[idx++] = Byte.parseByte("-" + builder.toString(), 2);
            }
        }
        return new String(bytes);
    }

    // --------------------------------------------------- 测试函数 -------------------------------------------------------------------
    private static void testFunctions() {
        // int[][] matrix = getMatrix("00000001" + "00100011" + "01010001" + "01100111" + "10001001" + "10101011" + "11001101" + "11101111" + "00000001" + "00100011" + "01000101" + "01100111" + "10001001" + "10101011" + "11001101" + "11101111");
        // showByHex(matrix);
        // String string = matrixToString(matrix);
        // System.out.println(string);
        // int[][] key = getMatrix("00000011" + "00100111" + "01010001" + "01100111" + "10001001" + "10101011" + "11001101" + "11101111" + "00000001" + "00100011" + "01000101" + "01100111" + "10001001" + "10101011" + "11001101" + "11101111");
        // showByHex(key);
        // int[][] xor = xor(matrix,key);
        // showByHex(xor);
        // System.out.println();
        // showByHex(SBox);
        // int[][] subBytes = SubBytes(matrix);
        // showByHex(subBytes);
        // int[][] shiftRows = ShiftRows(subBytes);
        // showByHex(shiftRows);
        // int[][] invshiftRows = InvShiftRows(subBytes);
        // showByHex(invshiftRows);
        // int[][] addRoundKey = AddRoundKey(matrix,subBytes);
        // showByHex(matrix);
        // showByHex(subBytes);
        // showByHex(addRoundKey);
        // // System.out.println(Multiple(0b01101011,0b10001101));
        // // System.out.println(MyTools.toString(184,2,8));
        // int[][] col = new int[][]{
        // 	{0xd4,0xe0,0xb8,0x1e},{0xbf,0xb4,0x41,0x27},{0x5d,0x52,0x11,0x98},{0x30,0xae,0xf1,0xe5}
        // };
        // int[][] mixColumns = MixColumns(col);
        // showByHex(mixColumns);
        // int[] wordCycle = wordCycle(new int[]{1,2,3,4});
        // for(int i : wordCycle){
        // 	System.out.print(i + ",");
        // }
        // System.out.println();
        // int[] sBoxReplace = SBoxReplace(wordCycle);
        // for(int i : sBoxReplace){
        // 	System.out.print(Integer.toBinaryString(i) + ",");
        // }
        // System.out.println();
        // int[] roundConstantXOR = roundConstantXOR(sBoxReplace,0);
        // for(int i : roundConstantXOR){
        // 	System.out.print(Integer.toBinaryString(i) + ",");
        // }
        // int[][] key = new int[][]{
        // 	{0x2b,0x28,0xab,0x09},//
        // 	{0x7e,0xae,0xf7,0xcf},//
        // 	{0x15,0xd2,0x15,0x4f},//
        // 	{0x16,0xa6,0x88,0x3c}
        // };
        // int[][][] subKeys = getSubKeys(key);
        // for(int i = 0; i < subKeys.length; i++){
        // 	showByHex(subKeys[i]);
        // }
        // int[] pArr = new int[]{0x32,0x43,0xf6,0xa8,0x88,0x5a,0x30,0x8d,0x31,0x31,0x98,0xa2,0xe0,0x37,0x07,0x34};
        // StringBuilder p = new StringBuilder();
        // for(int item : pArr){
        // 	p.append(MyTools.toString(item,2,8));
        // }
        // int[] cArr = new int[]{0x2b,0x7e,0x15,0x16,0x28,0xae,0xd2,0xa6,0xab,0xf7,0x15,0x88,0x09,0xcf,0x4f,0x3c};
        // StringBuilder c = new StringBuilder();
        // for(int item : cArr){
        // 	c.append(MyTools.toString(item,2,8));
        // }
        // String ciphertext = encryptCore(p.toString(),c.toString());
        // System.out.println(ciphertext);
        // showByHex(getMatrix(ciphertext));
        // String plaintext = decryptCore(ciphertext,c.toString());
        // System.out.println(plaintext);
        // showByHex(getMatrix(plaintext));
        // System.out.println("---------------------------------------------------------");
    }

    public static void main(String[] args) {
        // testFunctions();
        String plain = "0123456789 AES I love you!";
        String key = "10101110110110111010111011011011101011101101101110101110110110111010111011011011101011101101101110101110110110111010111011011011";
        String cipher = encrypt(plain, key);
        System.out.println("密文为:\n" + cipher);
        plain = decrypt(cipher, key);
        System.out.println("明文为:\n" + plain);
        System.out.println("注意,解密过程中,最后一部分不足16byte,末尾补$");
    }
}