The Salsa20 Cipher is a stream cipher which uses a 256-bit key and a 64-bit nonce. It was created by Daniel J. Bernstein in 2005. In 2008, ChaCha20 was released as a modification to Salsa20.
Salsa20 with Bouncy Castle and C# |
Coding
First we create a folder named "bc_salsa20", 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 Salsa20 { 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); Salsa20Engine cipher = new Org.BouncyCastle.Crypto.Engines.Salsa20Engine(); 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:
===Salsa20 Cipher == Message: Hello 123 IV: 0001020304050607 Key: DFA1FAF23B7A8ED8C0229CE3E8F29AC875742E0FE4D229DD45B543AFAEB87B1E [36H68jt6jtjAIpzj6PKayHV0Lg/k0indRbVDr664ex4=] Cipher (hex): 271EDAA4EDCBF00C36 Cipher (Base64): Jx7apO3L8Aw2 Plain: Hello 123
Notice that the cipher stream is the same length as the plaintext stream.