Java中的行转置密码列顺序

时间:2016-03-23 09:35:48

标签: java cryptography

我目前正在编写一些程序作为理解加密形式的方法,目前正在使用列编写行转置密码。我有程序能够获取一个键和一个消息,并从该表单中获得正确排序的2D数组。我遇到麻烦的是,创建一个数字串,允许程序知道要读取的列的顺序 - 如在更复杂的转置密码中,字母表中字符的位置决定列的顺序读入。解决方案可能很简单,但我遇到了很多麻烦。 我的计划如下所示:

public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    System.out.println("Enter a key up to 9 characters long: ");
    String key = s.nextLine().toUpperCase();
    System.out.println("Enter a message: ");
    String plainTextMessage = s.nextLine().toUpperCase().trim();
    plainTextMessage = plainTextMessage.replace(" ", "");
    System.out.println(plainTextMessage);
    int x = key.length();
    int y = (int) Math.ceil((double) plainTextMessage.length() / x);
    System.out.println("x = " + x + " y = " + y);
    char[][] arrayMsg = make2dArrayFromString(key, plainTextMessage, x, y);
    System.out.println(Arrays.deepToString(arrayMsg));
    String encrypted = encryptArray(key, arrayMsg, x, y);
    System.out.println("Encrypted message: " + encrypted);
}

public static char[][] make2dArrayFromString(String key, String plainTextMessage, int x, int y) {
    Scanner feed = new Scanner(plainTextMessage).useDelimiter("");
    char encryptArray[][] = new char[y][x];
    for (char[] encryptArray1 : encryptArray) {
        for (int j = 0; j < encryptArray1.length; j++) {
            char t;
            try {
                t = feed.next().charAt(0);
            } catch (Exception e) {
                t = 0;
            }
            encryptArray1[j] = t;
        }
    }
    return encryptArray;
}

public static String encryptArray(String key, char[][] arrayMsg, int x, int y) {
    String encryptedMsg = "";
    String alphaOrder = alphaSort(key);
    System.out.println("Numeric position of characters in key: " + alphaOrder);
    return encryptedMsg;
}

public static String alphaSort(String key) {
    int[] charOrder = new int[key.length()];
    for (int i = 0; i < key.length(); i++) {
        int alphaPos = key.charAt(i) - 65 + 1;
        charOrder[i] = alphaPos;
    }
    Arrays.sort(charOrder);
    String alphaOrder = Arrays.toString(charOrder);
    return alphaOrder;
}

输出

Enter a key up to 9 characters long: 
RIGHT
Enter a message: 
hello everyone
HELLOEVERYONE
x = 5 y = 3
[[H, E, L, L, O], [E, V, E, R, Y], [O, N, E, , ]]
Numeric position of characters in key: [71, 72, 73, 82, 84]

非常感谢。

0 个答案:

没有答案