实施充气城堡aes 256

我正在开发一个聊天应用程序。 主要function是以加密forms发送消息,当它们到达目的地时,它们可以被解密。 我遇到的问题是邮件在目的地没有被解密,但是它们以加密forms到达目的地。

代码如何工作:

  1. 客户端A向客户端B发送消息“Hello”…
  2. 当客户端A点击按钮“发送消息”时,我将该文本保存在字符串中,然后将该字符串与密钥和iv一起传递给方法加密,如下所示……

    en=enc.encrypt(msg.getBytes(), key.getBytes(), iv.getBytes()); 

    我将该字节( en )转换为字符串并将其发送到另一个客户端B.

  3. 当我打开另一个接收消息的类时,我得到字符串(en),然后再将其转换为字节,然后传递给方法Decrypt。 但每当我运行该项目时,它都无法运行。 试图在尝试捕获中做到这一点,但也没有工作。 也许是因为它已经在一个很大的尝试捕获声明已经使它更令人困惑。

我的代码:

 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); } } 

您经常使用String.getBytes() 。 这几乎可以确定您出错的位置。 getBytes()与平台有关,因此您可能在不同的系统上获得不同的字节。 此外,并非所有字节都是有效的字符编码。 因此,如果您的密钥/ IV由安全的随机字节(它们应该)组成,那么您的解密将失败…有时。

一般的答案是使用指定的字符编码(例如UTF-8)将字符转换为字节,使用base-64或hexadecimals等编码将字节转换为字符。