我想使用 Bouncy Castle 使用 AES/CCM 加密,但我不知道我在以下代码中做错了什么(密钥和 iv 是从它们的 HEXA 表示中获得的):
using System;
using System.Linq;
using System.Text;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
namespace Crypto.Tests {
class MainClass {
public static void Main (string[] args) {
var key = "D44EDA90DDCFA90216BDAC1559D704D336D371A3DA943E935315964D27CC91DC".ToByteArray();
var iv = "7B13E1A17861356401A3C15F4F0525C3".ToByteArray();
var nonSecretPayload = new byte[] { };
var plainText = Encoding.UTF8.GetBytes("Secret message!!!");
var cipher = new CcmBlockCipher(new AesFastEngine());
var parameters = new CcmParameters(
new KeyParameter(key), 64, iv, nonSecretPayload);
cipher.Init(true, parameters);
var cipherText = new byte[cipher.GetOutputSize(plainText.Length)];
var len = cipher.ProcessBytes(plainText, 0, plainText.Length, cipherText, 0);
cipher.DoFinal(cipherText, len);
Console.WriteLine(Convert.ToBase64String(cipherText));
Console.Read();
}
}
public static class StringExtentions {
public static byte[] ToByteArray(this string toTransform) {
return Enumerable
.Range(0, toTransform.Length / 2)
.Select(i => Convert.ToByte(toTransform.Substring(i * 2, 2), 16))
.ToArray();
}
}
}
执行上述代码会导致以下异常:
Unhandled Exception: System.ArgumentException: Destination array was not long enough.
Check destIndex and length, and the array's lower bounds.
at System.Array.Copy(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length, Boolean reliable)
at Org.BouncyCastle.Crypto.Modes.CcmBlockCipher.ProcessPacket(Byte[] input, Int32 inOff, Int32 inLen)
at Org.BouncyCastle.Crypto.Modes.CcmBlockCipher.DoFinal(Byte[] outBytes, Int32 outOff)
at Crypto.Tests.MainClass.Main(String[] args) in c:\Users\Emi\Documents\Projects\Crypto\Crypto.Tests\Main.cs:line 23