私はチャットアプリケーションに取り組んでいます。主な機能は、メッセージを暗号化された形式で送信することであり、宛先に到達すると復号化できます。私が抱えている問題は、メッセージが宛先で復号化されていないが、暗号化された形式で宛先に到達することです。
コードの仕組み:
- クライアント A はクライアント B にメッセージ「Hello」を送信します...
クライアントAが「メッセージを送信」ボタンをクリックすると、そのテキストを文字列に保存し、その文字列をキーとivとともにメソッドEncryptに渡します...
en=enc.encrypt(msg.getBytes(), key.getBytes(), iv.getBytes());
そのバイト (
en
) を文字列に変換して、他のクライアント B に送信します。メッセージを受信する他のクラスを開くと、文字列 (en) を取得し、それを再びバイトに変換して Decrypt メソッドに渡します。しかし、プロジェクトを実行するたびに機能しません。try catch でそれを実行しようとしましたが、うまくいきませんでした。おそらく、すでに大きな try catch ステートメントに含まれているため、さらに混乱しています。
私のコード:
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);
}
}