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="000102030405060708090A0B"; 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); ChaCha7539Engine cipher = new ChaCha7539Engine(); byte[] nonce = new byte[12]; Array.Copy(Convert.FromHexString(iv), nonce, 12); 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:
===ChaCha7539 Cipher == Message: Hello 123 IV: 000102030405060708090A0B Key: B1E23A9CDC11818C32FD12A756DF6D23C6B4D050255012FDD691B12F1053894F [seI6nNwRgYwy/RKnVt9tI8a00FAlUBL91pGxLxBTiU8=] Cipher (hex): 8A0D72D53C109536B7 Cipher (Base64): ig1y1TwQlTa3 Plain: Hello 123
Notice that the cipher stream is the same length as the plaintext stream.