package Demo_01; public class Cipher_Main { public static void main(String[] args) { //明文 String p = "Beijing2008OlympicGames"; //秘钥 int[][] key = {{1,4,3},{5,6}}; String cip =permutationCipher.run(p, key); System.out.println(cip); int[][] rekey = decryptKey.run(key); String cy =permutationCipher.run(cip, rekey); System.out.println(cy); } } package Demo_01; public class permutationCipher { public static String run(String p,int[][] key) { // //明文 // String p = "Beijing2008OlympicGames"; // // //秘钥 // int[][] key = {{1,4,3},{5,6}}; //得到最大列 int column = key[key.length-1][(key[key.length-1].length)-1]; //得到最大行 int row = calcRow(p,column); //通过key得到一维加密数组,方便后续加密 int[] keyArry = calcKeyArry(key); //生成明文p矩阵 char[][]Mp = calcMp(p,column,row); //生成密文矩阵 char[][]Mk = transposition(Mp,keyArry); //密文 String cip = ""; for(char[] xd :Mk){ for(char xc :xd){ cip+=xc; } } return cip; } //生成密文矩阵 private static char[][] transposition(char[][] mp, int[] keyArry) { char[][] newmp = new char[mp.length][mp[0].length]; for (int i = 1; i < keyArry.length; i++) { for (int j = 0; j < mp.length; j++) { newmp[j][i-1]=mp[j][(keyArry[i])-1]; } } return newmp; } //生成明文矩阵 private static char[][] calcMp(String p, int column, int row) { char[][] Mp = new char [row][column]; char[] c = p.toCharArray(); for(int i=0, j=0, k=0; i<c.length ;i++){ Mp[j][k] = c[i]; k++; if(k==column){ j++; k=0; } } return Mp; } //为rekey赋值 , rekey下标为被置换的列 ,值为要置换到的列,rekey[0]=0 private static int[] calcKeyArry(int[][] key) { int[] rekey = new int[key[key.length-1][(key[key.length-1].length)-1]+1]; //两层循环遍历key for(int a[]: key){ for(int i = 0 ; i<=a.length-1; i++){ //判断是否为最后一个,若是值为第一个,否为下一个 if(i==a.length-1){ rekey[a[i]] = a[0]; }else{ rekey[a[i]]=a[i+1]; } } } //不用置换的 for(int i = 0 ; i<=rekey.length-1; i++){ if(rekey[i]==0){ rekey[i] = i; } } return rekey; } //计算最大列 private static int calcRow(String p, int column) { char[] a = p.toCharArray(); int b = a.length; int c; if(b%column==0){ c = b/column; }else{ c = (b/column)+1; } return c; } } package Demo_01; public class decryptKey { public static int[][] run(int[][] key){ //待续........... int[][] rekey = new int[key.length][]; return rekey; } }
时间: 2024-10-13 12:32:39