Mitch Mitch - 1 year ago 52
Java Question

Appending a byte[] to the end of another byte[]

I have two

arrays which are of unknown length and I simply want to append one to the end of the other, i.e.:

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

I have tried using
but can't seem to get it to work.

Answer Source

Using System.arraycopy(), something like the following should work:

// 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);