array out of bounds adding a byte array to another

Victorcx

New Member
Working on a bit of crypto and ran into an array out of bounds exception. I traced through it a few times on paper and all seems okay to me so i cant really determine the origin of the error. If anyone could help that would be awesome!\[code\] static byte[] encrypt(byte[] ptBytes, javax.crypto.SecretKey key, byte[] IV){ byte [] ct; byte [] pt; byte [] ptBlock, ctBlock; int bytes; //the number of bytes left over in the last block // this comes into play w/ the last 2 blocks witht the swap and stuff //get the extra bytes in case last block of plain text isn't whole bytes = ptBytes.length%16; //pad the plain text array to proper length pt = Arrays.copyOf(ptBytes, (((ptBytes.length )/16) + 1) * 16 ); System.out.println(Arrays.toString(pt)); //ctBlock = one block of cipher text ctBlock = new byte [16]; //make ct the length of the padded pt ct = new byte [pt.length]; //do the encryption //i is for the current block of plain / cipher text we are on for( int i = 1; i <= ((ptBytes.length )/16)+1; i++){ if( i == 1 ){ //make ptBlock the first block of the entire plain text ptBlock = Arrays.copyOfRange(pt, 0, (i*16)); //since i = 1 do the XOR to get new plain text with IV for (int j = 0; j < ptBlock.length - 1; j++){ ptBlock[j] = (byte)(ptBlock[j] ^ IV[j]); } //now time to do the encryption between the current block of plain text and the key try { ctBlock = AES.encrypt(ptBlock, key); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //now put the cipher text block we just got into the final cipher text array for( int k = 0; k < ctBlock.length; k++){ ct[k] = ctBlock[k]; } } else{ //make ptBlock the current number block of entire plain text ptBlock = Arrays.copyOfRange(pt, (i-1)*16, (i*16)); //now XOR the plain text block with the prior cipher text block for(int j = 0; j < ptBlock.length - 1; j++){ ptBlock = (byte) (ptBlock[j] ^ ctBlock[j]); } //now time to do the encryption between the current block of plain text and the key try { ctBlock = AES.encrypt(ptBlock, key); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //now put the cipher text block we just got into the final cipher text array for( int k = (i-1)*16; k < (i*16)-1; k++){ ct[k] = ctBlock[k-16]; } } } return ct;}\[/code\]it says the error is on this line\[code\]ct[k] = ctBlock[k-16];\[/code\]which doesnt make much sense. The array ct is of length 48, and ctBlock is len 16 and in the case of where this error is in the for loop, i is equal to 2 or 3 so i am adding a size 16 byte array to either the 2nd third of the array ct or the 3rd third. and like i said i traced it out on paper and it seemed legit so idk!Thanks in advance!
 
Back
Top