BouncyCastle AES / CCM шифрование неверный результат - PullRequest
0 голосов
/ 16 октября 2018

Я пытаюсь использовать AES / CCM BouncyCastle с 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);

он функционирует.

...