【发布时间】:2022-06-11 18:06:37
【问题描述】:
我已经使用 Bouncy Castle 库实现了 AES 256 ECB 加密和解密。我能够加密数据,但无法解密密文。它抛出一个错误,说“Org.BouncyCastle.Crypto.DataLengthException:最后一个块在解密中不完整”。以下是我的加密和解密代码;
public byte[] encrypt(byte[] skey, byte[] data)
{
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
new AesEngine(), new Pkcs7Padding());
cipher.Init(true, new KeyParameter(skey));
int outputSize = cipher.GetOutputSize(data.Length);
byte[] tempOP = new byte[outputSize];
int processLen = cipher.ProcessBytes(data, 0, data.Length, tempOP, 0);
int outputLen = cipher.DoFinal(tempOP, processLen);
byte[] result = new byte[processLen + outputLen];
Array.Copy(tempOP, 0, result, 0, result.Length);
return result;
}
public byte[] decrypt(byte[] skey, byte[] data)
{
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
new AesEngine(), new Pkcs7Padding());
cipher.Init(false, new KeyParameter(skey));
int outputSize = cipher.GetOutputSize(data.Length);
byte[] tempOP = new byte[outputSize];
int processLen = cipher.ProcessBytes(data, 0, data.Length, tempOP, 0);
int outputLen = cipher.DoFinal(tempOP, processLen);
byte[] result = new byte[processLen + outputLen];
Array.Copy(tempOP, 0, result, 0, result.Length);
return result;
}
【问题讨论】:
-
不可重现,将
encrypt()和decrypt()的调用连同测试数据(密钥、明文、密文)一起发布。
标签: c# encryption aes bouncycastle ecb