HC-128 is a stream cipher that was created in 2004 by Hongjun Wu. It has a 128-bit key and a 128-bit nonce value. It focuses on bulk encryption in software at high speeds and also provides strong security levels. It has a performance level of around 1.93 bits/cycle.
HC-128 with Bouncy Castle and C# |
Coding
First we create a folder named "bc_hc128", 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 HC128 { 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="00112233445566778899AABBCCDDEEFF"; var size=128; if (args.Length >0) msg=args[0]; if (args.Length >1) iv=args[1]; try { var plainTextData=System.Text.Encoding.UTF8.GetBytes(msg); var cipher = new HC128Engine(); byte[] nonce = new byte[16]; Array.Copy(Convert.FromHexString(iv), nonce, 16); CipherKeyGenerator keyGen = new CipherKeyGenerator(); keyGen.Init(new KeyGenerationParameters(new SecureRandom(), size)); KeyParameter keyParam = keyGen.GenerateKeyParameter(); ParametersWithIV keyParamIV = new ParametersWithIV(keyParam,nonce); cipher.Init(true,keyParamIV); int outputSize = plainTextData.Length; byte[] cipherTextData = new byte[outputSize]; cipher.ProcessBytes(plainTextData, 0, plainTextData.Length, cipherTextData, 0); var rtn = cipherTextData; // Decrypt cipher.Init(false,keyParamIV); outputSize = cipherTextData.Length; plainTextData = new byte[outputSize]; cipher.ProcessBytes(cipherTextData, 0, cipherTextData.Length,plainTextData, 0); var pln=plainTextData; Console.WriteLine("=== {0} ==",cipher.AlgorithmName); Console.WriteLine("Message:\t\t{0}",msg); Console.WriteLine("IV:\t\t\t{0}",iv); Console.WriteLine("Key size:\t\t{0} bits",size); 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.ASCII.GetString(pln).TrimEnd('\0')); } catch (Exception e) { Console.WriteLine("Error: {0}",e.Message); } } } }
A sample run is:
=== HC-128 == Message: Hello 123 IV: 00112233445566778899AABBCCDDEEFF00 Key size: 128 bits Key: 7CBE50F10F29A58CED90A53EE96D2F23 [fL5Q8Q8ppYztkKU+6W0vIw==] Cipher (hex): 86E0EDFDB44ED63C4E Cipher (Base64): huDt/bRO1jxO Plain: Hello 123