我正在开发一个聊天应用程序。主要功能是以加密形式发送消息,当它们到达目的地时可以解密。我遇到的问题是,消息在到达目的地后无法解密,但它们以加密形式到达了目的地。
代码如何工作:
- Client A sends message "Hello" to client B...
When Client A clicks on button "Send message" I save that text in a String and then that String is passed along with key and iv to the method Encrypt like this...
en=enc.encrypt(msg.getBytes(), key.getBytes(), iv.getBytes());
I convert that byte (
en
) into string and sends it to the other client B.When I open the other class where I receive the message I get the string (en) and then again converts it into bytes which is passed to the method Decrypt. But whenever I run the project it doesn't work. Tried to do that in try catch but didn't worked either. Maybe because it is already in a big try catch statement already which makes it even more confusing.
我的代码:
package com.socket;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
public class Encrypt {
public Encrypt() {
}
public static byte[] cipherData(PaddedBufferedBlockCipher cipher, byte[] data)
throws Exception {
int minSize = cipher.getOutputSize(data.length);
byte[] outBuf = new byte[minSize];
int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
int length2 = cipher.doFinal(outBuf, length1);
int actualLength = length1 + length2;
byte[] result = new byte[actualLength];
System.arraycopy(outBuf, 0, result, 0, result.length);
return result;
}
public static byte[] decrypt(byte[] cipher, byte[] key, byte[] iv)
throws Exception {
PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(
new CBCBlockCipher(new AESEngine()));
CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
aes.init(false, ivAndKey);
return cipherData(aes, cipher);
}
public byte[] encrypt(byte[] plain, byte[] key, byte[] iv) throws Exception {
PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(
new CBCBlockCipher(
new AESEngine()));
CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
aes.init(true, ivAndKey);
return cipherData(aes, plain);
}
}
Exception
,而是只抛出必要的受检异常(IllegalStateException, InvalidCipherTextException
)。 - Duncan Jones