java - 以 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(通过添加空字节或任何内容)。在此先感谢您的帮助。
解决方案
我不知道这是否过于复杂,但这就是我想出的:
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
更容易使用)。
推荐阅读
- javascript - 调用超类方法的更好方法
- jquery - 如何使复选框的行为类似于使用相同名称的单选按钮
- d3.js - 是否可以跳过 D3.js 树中的节点?
- android - 没有带有cordova> = 7的AndroidManifest.xml文件
- php - 将 Cassandra UUID 对象转换为 PHP 字符串
- java - 如何创建具有 n 深度的 Freemarker 模板?
- python - 在逗号分隔值的熊猫中拆分列但保持顺序
- python - 每行 Numpy 动态切片
- sql - 如何在 PL/SQL Oracle 中获取每年日期范围的数字总和
- hibernate - Hibernate DB2 方言分页问题