为了更好地理解CBC和CTS,我试图改造我自己的类,它可以加密和解密而不使用java的内置CTS模式。我使用AES包装类作为底层算法,但使用CTS作为操作模式。到目前为止,我一直在研究加密方法,但不知道从那里去哪里。我不确定如何在CTS模式结束时实现块的交换。
以下是我目前为我的加密方法编写的代码(并且不用担心它可以100%运行的AES类):
static byte[] encrypt(byte[] ptBytes, javax.crypto.SecretKey key, byte[] IV){
byte [] ct;
byte [] pt;
byte [] ptBlock, ctBlock;
//pad the array to proper length
pt = Arrays.copyOf(ptBytes, (int) (Math.ceil( ( ptBytes.length )/16)*16) );
//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 < (int) ((Math.ceil( ( 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)-1);
//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)-1);
//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;
}
如果有人能够对如何完成这种方法有所了解,那将是很好的,因为我仍在学习CBC / CTS的来龙去脉
谢谢!