Bouncy Castle を使用して AES/CCM 暗号化を使用したいのですが、次のコードで何が間違っているのかわかりません (key と 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