进行一点加密工作,并遇到了超出范围的异常数组。我在纸上找了几次,对我来说一切都还好,所以我不能真正确定错误的起因。如果有人可以帮助,那就太好了!
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[i] = (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;
}
它说错误在这条线上
ct[k] = ctBlock[k-16];
这没有多大意义。数组ct的长度为48,而ctBlock的长度为len 16,在for循环中出现此错误的情况下,i等于2或3,因此我将16字节大小的数组添加到数组的第二个三分之一数组ct或第3个三分之一。就像我说的,我在纸上找到了它,这似乎很合法!
提前致谢!
最佳答案
考虑i = 3
的情况。
for( int k = (i-1)*16; k < (i*16)-1; k++){
ct[k] = ctBlock[k-16];
}
这里 -
k从32开始
条件变为32
ctBlock
的数组索引变为32-16 = 16,而且很糟糕!数组索引超出范围!快速解决 -
for( int k = (i - 1) * 16; k < (i * 16) - 1; k++){
ct[k] = ctBlock[k - (16 * (i - 1))];
}