Java Fill数组每次2个字节

时间:2018-09-07 01:11:35

标签: java arrays byte

我正在尝试填充一个字节数组,一次填充2个字节。我的硬件是密码学硬件。我要使用密钥从给定的密文中找到纯文本。密钥为2个字节长。纯文本使用许多时间片进行了加密。重复密钥,直到其与纯文本一样长。我得到了密钥的前2个字节,现在我只需要重复一次,直到它与密文/纯文本一样长。

密文长度与纯文本长度相同,为640138。密钥也应为该长度,但是在应用以下解决方案后得到的密钥长度为640144。下面而不是Math.max给出错误String.checkBoundsBeginEnd。 我必须将其转换为字符串,因为构建器的类型为StringBuilder。在这种情况下,“结果”是关键。

我如何使密钥与密文长度一样长?

    byte[] cipherText = Files.readAllBytes(Paths.get("src/cipher3.bmp"));
    byte[] plainText = new byte[cipherText.length];

    byte[] pText = new byte[]{'B', 'M'};
    byte[] key = new byte[pText.length];
    for(int i = 0; i < pText.length; i++){
        key[i] = (byte)(cipherText[i] ^ pText[i]);
    }
    String keyString = Arrays.toString(key);
    System.out.println("The key " + keyString);
    System.out.println("First two in ptext"+ Arrays.toString(pText));
    System.out.println(plainText.length);

    String plainlength = (String) Arrays.toString(new int[]{plainText.length});
    System.out.println(plainlength);
    StringBuilder builder = new StringBuilder(cipherText.length);
    while(builder.length() < cipherText.length){
        builder.append(keyString.substring(0, Math.max(keyString.length(), builder.length() -cipherText.length)));
    }
    String result = builder.toString();
    System.out.println(result);
    System.out.println(result.length());//this gives 640144

1 个答案:

答案 0 :(得分:2)

Math.min应该用于正确填充。

  

java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-640138

为您提供有关错误的线索。 输入应用于subString方法,显然必须为Math.min(keyString.length(), builder.length() -cipherText.length。由于cipherText的长度必须大于或等于builder的长度,因此应交换参数以给出正确的结果。

public class Fill2ByteToArray {
    public static void main(String[] args) throws IOException {
        int targetLength = 640138;
        byte[] cipherText = new byte[targetLength];
        for (int i = 0; i < cipherText.length; i++) {
            cipherText[i] = Integer.valueOf(i).byteValue();
        }
        byte[] plainText = new byte[cipherText.length];

        byte[] pText = new byte[] { 'B', 'M' };
        byte[] key = new byte[pText.length];
        for (int i = 0; i < pText.length; i++) {
            key[i] = (byte) (cipherText[i] ^ pText[i]);
        }
        String keyString = Arrays.toString(key);
        System.out.println("The key " + keyString);
        System.out.println("First two in ptext" + Arrays.toString(pText));
        System.out.println(plainText.length);

        String plainlength = (String) Arrays.toString(new int[] { plainText.length });
        System.out.println(plainlength);
        StringBuilder builder = new StringBuilder(cipherText.length);
        while (builder.length() < cipherText.length) {
            builder.append(keyString.substring(0, Math.min(keyString.length(), cipherText.length-builder.length())));
        }
        String result = builder.toString();
        System.out.println(result);
        System.out.println(result.length());
    }
}