Supereme
Supereme

Reputation: 2409

How to append no. of bytes to a byte array?

I am doing a project in 'Steganography' in which I want to encrypt the contents of file using 'Blowfish' algorithm and then want to embed the encrypted text in the image and do the reverse procedure for extracting the image.
The 'update' method from class 'Cipher' encrypts only some no. of bytes but, here I want all the bytes(encrypted contents) of the file in only one array. Same is the case with 'update' method in decryption. This array later will be passed to a method in which I embed the text in the image and extract when required.So what can be the better approach towards this problem?
Thank you.

Upvotes: 1

Views: 6393

Answers (1)

Will Hartung
Will Hartung

Reputation: 118641

Most ciphers are streaming ciphers. They can take blobs of data and stream out results as it encrypt/decrypts them. The Java Cipher class works this way. You call update(..) with a block of data, and it returns a block of encrypted data. When you reach the end of your input data, you call the final(...) method.

Now, if you wish to accumulate all of your data in to a single binary buffer, and encrypt it all at once, that works fine also. But in the end, either way works, the cipher doesn't care if it encrypts 1 byte at a time or 1MB at a time.

If you simply want to know how to append byte arrays, you simply create a new byte array that has a length equal to the sum of the sizes of the arrays you wish to append, then use System.arraycopy to move copy the original arrays.

byte[] newbuf = new byte[oldbuf1.length + oldbuf2.length];
System.arraycopy(oldbuf1, 0, newbuf, 0, oldbuf1.length);
System.arraycopy(oldbuf2, 0, newbuf, oldbuf1.length, oldbuf2.length);

If you're going to do that a lot, and you have the memory to spare, it's better to accumulate your chunks of data in to disparate byte buffers, stuff them in a List, and then do your final merge just once.

int sum = 0;
for(byte[] ba : arraysList) {
    sum = sum + ba.length;
}
byte[] newbuf = new byte[sum];
int curpos = 0;
for(byte[] ba : arraysList) {
    System.arraycopy(ba, 0, newbuf, curpos, ba.length);
    curpos = curpos + ba.length;
}

(Code not tested, should work, don't think there's any 1-offs in there.)

Upvotes: 5

Related Questions