我正在尝试使用BouncyCastle的AES / CCM和C#进行加密,然后解密消息。
解密结果与原始消息不匹配。对于输入消息“测试消息”,加密和解密后的结果为“ dGVzdCBtZXNzYWdl”。
代码如下:
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using System;
namespace Test
{
class Program
{
public static void encrypt(byte[] keyString, byte[] inputBytes, byte[] iv)
{
//Set up
AesEngine engine = new AesEngine();
CcmBlockCipher cipher = new CcmBlockCipher(engine);
KeyParameter keyParam = new KeyParameter(keyString);
var parameters = new AeadParameters(keyParam, 8, iv, keyString);
// Encrypt
cipher.Init(true, parameters);
byte[] outputBytes = new byte[cipher.GetOutputSize(inputBytes.Length)];
int length = cipher.ProcessBytes(inputBytes, 0, inputBytes.Length, outputBytes, 0);
cipher.DoFinal(outputBytes, length); //Do the final block
string encryptedInput = Convert.ToBase64String(outputBytes);
//Decrypt
cipher.Init(false, parameters);
byte[] comparisonBytes = new byte[cipher.GetOutputSize(outputBytes.Length)];
length = cipher.ProcessBytes(outputBytes, 0, outputBytes.Length, comparisonBytes, 0);
cipher.DoFinal(comparisonBytes, length); //Do the final block
string result = Convert.ToBase64String(comparisonBytes);
}
static void Main(string[] args)
{
string message = "test message";
var input = System.Text.Encoding.UTF8.GetBytes(message);
var key = new Byte[]
{
0xD4, 0x4E, 0xDA, 0x90, 0xDD, 0xCF, 0xA9, 0x02,
0x16, 0xBD, 0xAC, 0x55, 0x9D, 0x70, 0x4D, 0x33,
0x6D, 0x37, 0x1A, 0x3D, 0xA9, 0x43, 0xE9, 0x35
};
var iv = new byte[]
{
0x7B, 0x13, 0xE1, 0xA1, 0x78, 0x61, 0x35, 0x64,
0x01, 0xA3, 0xC1, 0x5F
};
encrypt(key, input, iv);
}
}
}
感谢任何指向失败根源的指针。
更新 错误在这里:
string result = Convert.ToBase64String(comparisonBytes);
一次替换为:
string result = System.Text.Encoding.UTF8.GetString(comparisonBytes);
它起作用。