将一个字节[]附加到另一个字节的末尾[]

2022-09-01 01:11:50

我有两个长度未知的数组,我只想将一个附加到另一个数组的末尾,即:byte[]

byte[] ciphertext = blah;
byte[] mac = blah;
byte[] out = ciphertext + mac;

我尝试过使用,但似乎无法使其正常工作。arraycopy()


答案 1

使用 System.arraycopy(),如下所示的内容应该可以正常工作:

// create a destination array that is the size of the two arrays
byte[] destination = new byte[ciphertext.length + mac.length];

// copy ciphertext into start of destination (from pos 0, copy ciphertext.length bytes)
System.arraycopy(ciphertext, 0, destination, 0, ciphertext.length);

// copy mac into end of destination (from pos ciphertext.length, copy mac.length bytes)
System.arraycopy(mac, 0, destination, ciphertext.length, mac.length);

答案 2

也许是最简单的方法:

ByteArrayOutputStream output = new ByteArrayOutputStream();

output.write(ciphertext);
output.write(mac);

byte[] out = output.toByteArray();