我需要使用CBC Rijndael加密对文本进行编码/解码。
输入: 在这个looooooooooooooooooo000000000ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooongong String String
编码输入?†'Ú½m - AŽyÝ¢ƒô] 5X-å;'Bdž。Ìμ¼è¼ÈíÖXÈ*©Ã¼ç-hKBμ$híƒEu-ȸU¤'AÓÈÿ?Ÿûä¸: ?OW B个ÐZ²ñ ,ZAE(C'®5ÐixRópE%€。@vhrm6μ5©BS?Ç¡$q¿J^÷克的“e†ì?? BT I%q'ÕQÚ5μã?ƒ
已解码的输入 “这个力量在这个looooooooooooooooooo000000000oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo”中强大了 - 并且代替结尾的32个空格(字节值为0)
我错过了最后的字节。谁能告诉我为什么?
这是我的代码:
公共类BouncyDecoder {
byte[] IV = null;
byte[] encryptionKey = null;
Cipher cipher;
SecretKeySpec key;
BlockCipher blockCipher;
ParametersWithIV _param;
PaddedBufferedBlockCipher mode;
int blockSize;
public BouncyDecoder() {
Security.addProvider(new BouncyCastleProvider());
try {
IV = "1234567891234567891234567891234".getBytes("UTF-8");
encryptionKey = "1234567891123453456789123456781".getBytes("UTF-8");
blockCipher = new CBCBlockCipher(new RijndaelEngine(256));
_param = new ParametersWithIV(new KeyParameter(encryptionKey), IV);
mode = new PaddedBufferedBlockCipher(blockCipher);
blockSize = blockCipher.getBlockSize();
} catch (Exception e) {
}
}
public byte[] decrypt(byte[] encodedText) {
byte[] decoded = new byte[mode.getOutputSize(encodedText.length)];
try {
mode.init(false, _param);
int bytesProcessed = 0;
int i=0;
for (i = 0; i < (encodedText.length / 32) ; i++){
bytesProcessed += mode.processBytes(encodedText, i * blockSize, blockSize, decoded, bytesProcessed);
}
mode.doFinal(decoded, (i-1)*blockSize);
} catch (Exception e) {
}
return decoded;
}
public byte[] encrypt(byte[] normalText) {
byte[] encryptedText = new byte[mode.getOutputSize(normalText.length)];
try {
mode.init(true, _param);
int bytesProcessed = 0;
int i=0;
for (i = 0; i < (normalText.length / 32); i++) {
bytesProcessed += mode
.processBytes(normalText, i * blockSize, blockSize, encryptedText, bytesProcessed);
}
mode.doFinal(encryptedText, (i-1)*blockSize);
} catch (Exception e) {
e.printStackTrace();
}
return encryptedText;
}
}
答案 0 :(得分:1)
你的循环似乎没有处理输入字符串中的所有字节:
for (i = 0; i < (normalText.length / 32); i++) {
bytesProcessed += mode
.processBytes(normalText, i * blockSize, blockSize, encryptedText, bytesProcessed);
}
它只处理从0到(text.Length/32)*blockSize
的字节。
因此,如果输入数组的长度为35个字节,则永远不会处理最后3个字节。
如何使用这样的东西:
bytesProcessed = mode.processBytes(normalText, 0, normalText.length, encryptedText,0);
//second argument of doFinal is offset in output buffer.
mode.doFinal(encryptedText, bytesProcessed);
如果这个工作正常,你肯定会知道问题是循环计数器中的一个错误。
更新或者如果您想一次加密一个块,可以尝试这样的事情:
for(int i=0; i<=(normalText.length/blockSize); i++) {
int offset = i*blockSize;
//To handle last block of bytes in input
int len = Math.min(blockSize,normalText.length-offset);
bytesProcessed += mode.processBytes(normalText,offset,len,encryptedText,bytesProcessed);
}
mode.doFinal(encryptedText, bytesProcessed);
解密也是如此