Examples for decrypting message

using System;
using System.Linq;
using System.Text;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
 
namespace DecryptionExample
{
    // You need to install bccrypto-csharp from BouncyCastle. Please see BouncyCastle page.
    class Program
    {
        static void Main(string[] args)
        {
            string keyFromConfiguration = "000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f";
 
            // Data from server
            string ivFromHttpHeader = "000000000000000000000000";
            string authTagFromHttpHeader = "CE573FB7A41AB78E743180DC83FF09BD";
            string httpBody = "0A3471C72D9BE49A8520F79C66BBD9A12FF9";
 
            // Convert data to process
            byte[] key = ToByteArray(keyFromConfiguration);
            byte[] iv = ToByteArray(ivFromHttpHeader);
            byte[] authTag = ToByteArray(authTagFromHttpHeader);
            byte[] encryptedText = ToByteArray(httpBody);
            byte[] cipherText = encryptedText.Concat(authTag).ToArray();
 
            // Prepare decryption
            GcmBlockCipher cipher = new GcmBlockCipher(new AesFastEngine());
            AeadParameters parameters = new AeadParameters(new KeyParameter(key), 128, iv);
            cipher.Init(false, parameters);
 
            // Decrypt
            var plainText = new byte[cipher.GetOutputSize(cipherText.Length)];
            var len = cipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0);
            cipher.DoFinal(plainText, len);
            Console.WriteLine(Encoding.ASCII.GetString(plainText));
        }
 
        static byte[] ToByteArray(string HexString)
        {
            int NumberChars = HexString.Length;
            byte[] bytes = new byte[NumberChars / 2];
            for (int i = 0; i < NumberChars; i += 2)
            {
                bytes[i / 2] = Convert.ToByte(HexString.Substring(i, 2), 16);
            }
            return bytes;
        }
    }
}

Last updated