2

我想使用 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
4

2 回答 2

1

当它试图从你的随机数生成一个计数器 IV 时,它在充气城堡中崩溃了,因为它期待一个 (BlockSize - 1) 或更小的随机数,例如增量数字。如果您从 iv 中删除一个字节,它就可以工作。

   var iv = "7B13E1A17861356401A3C15F4F0525".ToByteArray();
于 2012-08-20T13:32:50.700 回答
-1

我不相信这些台词做你认为他们做的事,

var key = "D44EDA90DDCFA90216BDAC1559D704D336D371A3DA943E935315964D27CC91DC".ToByteArray(); 
var iv = "7B13E1A17861356401A3C15F4F0525C3".ToByteArray(); 

你可能想要的更像是,

var key =
{
    0xD4, 0x4E, 0xDA, 0x90, 0xDD, 0xCF, 0xA9, 0x02,
    0x16, 0xBD, 0xAC, 0x55, 0x9D, 0x70, 0x4D, 0x33,
    0x6D, 0x37, 0x1A, 0x3D, 0xA9, 0x43, 0xE9, 0x35,
    0x31, 0x59, 0x64, 0xD2, 0x7C, 0xC9, 0x1D. 0x0C
}; 

var iv =
{
    0x7B, 0x13, 0xE1, 0xA1, 0x78, 0x61, 0x35, 0x64,
    0x01, 0xA3, 0xC1, 0x5F, 0x4F, 0x05, 0x25, 0xC3
}; 

此外,您的密钥长度无效(我在最后添加了 0 C)。

于 2012-08-20T13:04:11.710 回答