欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Matrix Transposition Cipher,,package mtci

来源: javaer 分享于  点击 32943 次 点评:184

Matrix Transposition Cipher,,package mtci


package mtcipher;import java.util.Scanner;public class MTcipher {    public static void main(String[] args) {        System.out.println("***Please input the Key:");        Scanner key_in = new Scanner(System.in);        String key = key_in.next();        System.out                .println("Key memorized! \\n \\n***Please input the plaintext:");        Scanner plain_in = new Scanner(System.in);        String plain = plain_in.next();        String ciphertext = encrypt(plain, key);        System.out.println("===The ciphertext is: " + ciphertext + "\\n");        System.out.println("***Please input the ciphertext:");        Scanner cipher_in = new Scanner(System.in);        String cipher = cipher_in.next();        String plaintext = decrypt(cipher, key);        System.out.println("===The plaintext is: " + plaintext);    }    static String encrypt(String p, String k) {        String row1 = p.substring(0, 4), row2 = p.substring(4, 8), row3 = p                .substring(8, 12), row4 = p.substring(12, 16);        String col[] = new String[4];        for (int i = 0; i < 4; i++) {            col[i] = (row1.substring(i, i + 1) + row2.substring(i, i + 1)                    + row3.substring(i, i + 1) + row4.substring(i, i + 1));        }        String k1 = k.replaceAll(",", "");        String cc[] = new String[4];        for (int j = 0; j < 4; j++) {            int a = Integer.parseInt(k1.substring(j, j + 1));            cc[j] = col[a - 1];        }        String c = new String(cc[0] + cc[1] + cc[2] + cc[3]);        return c;    }    static String decrypt(String C, String k) {        String cc[] = { C.substring(0, 4), C.substring(4, 8),                C.substring(8, 12), C.substring(12, 16) };        String k1 = k.replaceAll(",", "");        String col[] = new String[4];        for (int j = 0; j < 4; j++) {            int a = Integer.parseInt(k1.substring(j, j + 1));            col[a - 1] = cc[j];        }        String row[] = new String[4];        for (int i = 0; i < 4; i++) {            row[i] = col[0].substring(i, i + 1) + col[1].substring(i, i + 1)                    + col[2].substring(i, i + 1) + col[3].substring(i, i + 1);        }        String P = new String(row[0] + row[1] + row[2] + row[3]);        return P;    }}//该片段来自于http://byrx.net
相关栏目:

用户点评