为了更好地理解 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 的来龙去脉
谢谢!