古典密码学之置换

来源:互联网 发布:淘宝找黑客改成绩 编辑:程序博客网 时间:2024/04/30 16:44

这学期开了门课 叫信息安全技术。

写了个置换的算法。

挺麻烦的。

明文: 
attackpostponeduntiltwoamxyz
密钥:4312567
将明文保存排列成矩阵
4 3 1 2 5 6 7
a  t  t  a c  k  p
o s  t  p o n e
d u  n t   i  l   t
w o a m x y z
然后按照密钥的顺序按列读出就成了密文 ttnaaptmtsuoaodwcoixknlypetz
还可以继续对密文进行再次加密,不过还是不安全 =。=

Java:

package cryptography;public class PermutationCipher {//加密static String encypt(String plaintext, String key) {String cipherText = "";String[] cipher = new String[key.length()];plaintext = plaintext.trim();int row = (plaintext.length()) / (key.length());int column = key.length();// 将明文和密钥分别保存在char数组和整型变量中char[] chars = new char[plaintext.length()];plaintext.getChars(0, plaintext.length(), chars, 0);int keycode = Integer.parseInt(key);char[][] matrix = new char[row][column];// 将明文保存在矩阵中for (int i = 0; i < row; i++)for (int j = 0; j < column; j++) {matrix[i][j] = chars[i * column + j];}int n = keycode;int index = 0;// 根据密钥译成密文for (int m = 0; m < column; m++) {index = (int) (n / Math.pow(10, column - m - 1));n = (int) (n % Math.pow(10,column - m - 1)) ;cipher[index-1] = readColumn(matrix, m);}for (int i = 0; i < cipher.length; i++)cipherText += cipher[i];return cipherText;}static String readColumn(char[][] matrix, int column) {String str = "";for (int i = 0; i < matrix.length; i++)str += matrix[i][column];return str;}//解码static String decrypt(String cipherText, String key){String plainText = "";cipherText = cipherText.trim();int row = (cipherText.length()) / (key.length());int column = key.length();// 将密文和密钥分别保存在char数组和变量中char[] chars = new char[cipherText.length()];cipherText.getChars(0, cipherText.length(), chars, 0);int keycode = Integer.parseInt(key);//将密文保存在矩阵中char[][] matrix = new char[column][row];for(int i = 0 ; i < column ; i++)for(int j = 0 ; j < row ; j++)matrix[i][j] = chars[i*row + j];//根据密钥译出密文int index = 0;int n = keycode;char[][] matrix_plain = new char[row][column];for(int m = 0 ; m < column ; m++){index = (int) (n/Math.pow(10, column - 1 - m));n = (int) (n%Math.pow(10, column - m -1));writeColumn(matrix_plain,matrix,index-1,m);}String[] plains = new String[row];for(int k = 0 ; k < row ; k++){plains[k] = new String(matrix_plain[k]);plainText += plains[k];}return plainText;}static void writeColumn(char[][] matrix_dest , char[][] matrix_s,int dest,int source){for (int i = 0 ; i < matrix_dest.length ; i++){matrix_dest[i][source] = matrix_s[dest][i];}}public static void main(String[] args) {String s = "attackpostponeduntiltwoamxyz";String key = "4312567";String cipher = encypt(s, key);String plain  = decrypt(cipher,key);System.out.println("密文是"+cipher+"明文是"+plain);}}
去掉明文的空格没有实现。算法逻辑有多要优化的地方。

原创粉丝点击