首页 > 解决方案 > 以 16 字节为单位的过程数据

问题描述

我正在用java构建一个加密工具。我得到了这个方法:

public byte[] blockEncrypt(byte[] b) {
//...
}

它将一个 16 字节的数组作为参数。但我不希望用户自己拆分字节,所以我创建了这个方法:

public byte[] encrypt(final byte[] plain) {

    int remainder = plain.length % blockSize();
    // I create the final array of size modulo blockSize
    byte[] encrypted = new byte[plain.length - remainder + (remainder == 0 ? 0 : blockSize())];
    // Here the array is splitted 
    byte[][] splitted = CryptoUtil.splitBytes(plain, blockSize());

    // I pad the last block if the argument is not modulo blockSize (with '=')
    if (plain.length % blockSize() != 0) {
        byte[] last = new byte[blockSize()];
        CryptoUtil.fill(last, (byte) 0x3D);
        System.arraycopy(splitted[splitted.length - 1], 0, last, 0, splitted[splitted.length - 1].length);
        splitted[splitted.length - 1] = last;
    }

    for (int i = 0; i < splitted.length; i++) {
        System.arraycopy(blockEncrypt(splitted[i], 0), 0, encrypted, i * blockSize(), blockSize());
    }
    return encrypted;
}

这段代码根本不起作用(而且很乱)。我根本不在乎它是如何实现的,我只想处理参数中的所有数据,每 16 个字节 16 个字节。有没有人有这个方法?最后一个非完整块应调整为 16(通过添加空字节或任何内容)。在此先感谢您的帮助。

标签: javaarraysbytepadding

解决方案


我不知道这是否过于复杂,但这就是我想出的:

public List<byte[]> splitArray(byte[] array, int blockSize) {
    if (array.length < blockSize) {
        // shortcut if array is too small, will pad end with 0s
        return Arrays.asList(Arrays.copyOf(array, blockSize));
    } else if (array.length == blockSize) {
        // shortcut if array length is already blockSize
        return Arrays.asList(array);
    }
    List<byte[]> list = new ArrayList<>();
    int from = 0;
    int to;
    while ((to = from + blockSize) <= array.length) {
        // keep adding to list while array has another blockSize range of elements
        list.add(Arrays.copyOfRange(array, from, to));
        from = to;
    }
    if (from != array.length) {
        // array did not divide into blockSize evenly, fill last block
        // with remaining elements. Pads end with 0s
        byte[] leftOver = new byte[blockSize];
        System.arraycopy(array, from, leftOver, 0, array.length - from);
        list.add(leftOver);
    }
    return list;
}

我将返回类型从更改byte[][]List<byte[]>(我发现List更容易使用)。


推荐阅读