The Chacha20 Cipher is a stream cipher which uses a 256-bit key and a 64-bit nonce. ChaCha7539 is defined in RFC 7539 and uses a 256-bit (32 byte) key and 12 byte (96-bit) nonce.
ChaCha7539 with Bouncy Castle and C# |
Coding
First we create a folder named "bc_ChaCha7539", and then go into that folder.We can create a Dotnet console project for .NET 8.0 with:
dotnet new console --framework net8.0
This produces a Csproject file of:
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net8.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> </Project>
We then add the latest Bouncy Castle library:
dotnet add package BouncyCastle.Cryptography --version 2.2.1
The following is the coding:
namespace ChaCha7539 { using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; class Program { static void Main(string[] args) { var msg="Hello"; var iv="0001020304050607"; var size=256; if (args.Length >0) msg=args[0]; if (args.Length >1) iv=args[1]; try { var plainTextData=System.Text.Encoding.UTF8.GetBytes(msg); ChaChaEngine cipher = new Org.BouncyCastle.Crypto.Engines.ChaChaEngine(); byte[] nonce = new byte[8]; Array.Copy(Convert.FromHexString(iv), nonce, 8); CipherKeyGenerator keyGen = new CipherKeyGenerator(); keyGen.Init(new KeyGenerationParameters(new SecureRandom(), size)); KeyParameter keyParam = keyGen.GenerateKeyParameter(); ParametersWithIV keys = new ParametersWithIV(keyParam,nonce,0,nonce.Length); cipher.Init(true,keys); byte[] cipherTextData = new byte[plainTextData.Length]; cipher.ProcessBytes(plainTextData, 0, plainTextData.Length, cipherTextData, 0); var rtn = cipherTextData; // Decrypt cipher.Init(false,keys); plainTextData = new byte[cipherTextData.Length]; cipher.ProcessBytes(cipherTextData, 0, cipherTextData.Length,plainTextData, 0); var pln=plainTextData; Console.WriteLine("==={0} Cipher ==",cipher.AlgorithmName); Console.WriteLine("Message:\t\t{0}",msg); Console.WriteLine("IV:\t\t\t{0}",iv); Console.WriteLine("Key:\t\t\t{0} [{1}]",Convert.ToHexString(keyParam.GetKey()),Convert.ToBase64String(keyParam.GetKey())); Console.WriteLine("\nCipher (hex):\t\t{0}",Convert.ToHexString(rtn)); Console.WriteLine("Cipher (Base64):\t{0}",Convert.ToBase64String(rtn)); Console.WriteLine("\nPlain:\t\t\t{0}",System.Text.Encoding.UTF8.GetString(pln)); } catch (Exception e) { Console.WriteLine("Error: {0}",e.Message); } } } }
A sample run is:
===ChaCha20 Cipher == Message: Hello 123 IV: 0001020304050607 Key: 4A0011B99E835D749DC5D7D6BE1917A2D0139200697E6466AB70245F92BF1850 [SgARuZ6DXXSdxdfWvhkXotATkgBpfmRmq3AkX5K/GFA=] Cipher (hex): DBC927CEB3FB2B41C5 Cipher (Base64): 28knzrP7K0HF Plain: Hello 123
Notice that the cipher stream is the same length as the plaintext stream.