Initial version

This commit is contained in:
EonaCat 2025-07-05 22:03:33 +02:00
parent 70b2b6bd10
commit 063a50fdbe
13 changed files with 1685 additions and 124 deletions

91
.gitignore vendored
View File

@ -2,7 +2,7 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
@ -14,9 +14,6 @@
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
@ -24,14 +21,10 @@ mono_crash.*
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
@ -45,10 +38,9 @@ Generated\ Files/
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
# NUNIT
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
@ -63,9 +55,6 @@ project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
@ -91,7 +80,6 @@ StyleCopReport.xml
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
@ -133,6 +121,9 @@ _ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
@ -143,11 +134,6 @@ _TeamCity*
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
@ -195,8 +181,6 @@ PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
@ -221,14 +205,12 @@ BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
!*.[Cc]ache/
# Others
ClientBin/
@ -272,9 +254,6 @@ ServiceFabricBackup/
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
@ -295,17 +274,6 @@ node_modules/
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
@ -321,6 +289,10 @@ paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush personal settings
.cr/personal
@ -362,53 +334,10 @@ ASALocalRun/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
# ---> VisualStudioCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix

25
EonaCat.Crypto.sln Normal file
View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.14.36212.18 d17.14
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Crypto", "EonaCat.Crypto\EonaCat.Crypto.csproj", "{E08BA387-7F8B-4BCA-81CA-039173FF1DA9}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{E08BA387-7F8B-4BCA-81CA-039173FF1DA9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E08BA387-7F8B-4BCA-81CA-039173FF1DA9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E08BA387-7F8B-4BCA-81CA-039173FF1DA9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E08BA387-7F8B-4BCA-81CA-039173FF1DA9}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {5F85450B-2A48-4486-A2EB-CB5337BB99BF}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,633 @@
using EonaCat.Crypto.Hashing;
using EonaCat.Crypto.Helpers;
using System.Text;
namespace EonaCat.Crypto
{
public class EonaCatCrypto
{
private static readonly string _fileIdentifier = "Encrypted by EonaCat.Crypto => ";
private const int _blockSize = 64; // 512-bit block
private const int _keySize = 128; // 1024-bit key
private const int _numRounds = 48;
private const int _nonceSize = 24;
private const int _tagSize = 32; // HMAC-SHA256 tag size
private readonly byte[][] _roundKeys;
private readonly byte[] _hmacKey;
private static readonly byte[] _defaultSalt = RandomNumberGeneratorCustom.ComputeHash(Encoding.UTF8.GetBytes("EONACAT_CRYPTO_SPECIAL_KEY"));
public EonaCatCrypto(string key, byte[] salt = null)
{
if (key == null) throw new ArgumentNullException(nameof(key));
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
try
{
salt ??= _defaultSalt;
// Derive a master key using HKDF with the provided or default salt
byte[] masterKey = HkdfSha512DeriveKey(keyBytes, salt, _keySize);
try
{
_roundKeys = ExpandRoundKeysHKDF(masterKey);
_hmacKey = HkdfSha512DeriveKey(masterKey, salt, _keySize, info: Encoding.UTF8.GetBytes("EonaCat HMAC Key"));
}
finally
{
Array.Clear(masterKey, 0, masterKey.Length);
}
}
finally
{
Array.Clear(keyBytes, 0, keyBytes.Length);
}
}
private static byte[] HkdfSha512DeriveKey(byte[] inputKey, byte[] salt, int outputLength, byte[] info = null)
{
// HKDF Extract
byte[] prk;
using (var hmac = new HMACSHA512Custom(salt))
{
prk = hmac.ComputeHash(inputKey);
}
// HKDF Expand with optional info for domain separation
var okm = HkdfExpand(prk, info, outputLength);
Array.Clear(prk, 0, prk.Length); // Clear PRK for security
return okm;
}
// Constructor from fixed-length byte array key + optional salt
public EonaCatCrypto(byte[] key, byte[] salt = null)
{
if (key == null || key.Length != _keySize)
throw new ArgumentException($"EonaCat.Crypto: Key must be {_keySize} bytes (1024 bits)");
salt ??= _defaultSalt;
// Use HKDF to expand round keys and derive HMAC key with salt
_roundKeys = ExpandRoundKeysHKDF(key, salt);
_hmacKey = DeriveHmacKeyHKDF(key, salt);
Array.Clear(key, 0, key.Length);
}
public static void EncryptFile(string inputPath, string outputPath, EonaCatCrypto crypto)
{
if (!File.Exists(inputPath))
{
Console.WriteLine($"EonaCat.Crypto: Input file does not exist: {inputPath}");
return;
}
byte[] fileBytes = File.ReadAllBytes(inputPath); // Read original file bytes
byte[] encryptedBytes = crypto.Encrypt(fileBytes); // Encrypt file bytes
File.WriteAllBytes(outputPath, encryptedBytes); // Write encrypted bytes to output file
Console.WriteLine($"EonaCat.Crypto: File encrypted: {outputPath}");
}
public static void DecryptFile(string inputPath, string outputPath, EonaCatCrypto crypto)
{
if (!File.Exists(inputPath))
{
Console.WriteLine($"EonaCat.Crypto: Input file does not exist: {inputPath}");
return;
}
byte[] encryptedBytes = File.ReadAllBytes(inputPath); // Read encrypted file bytes
byte[] decryptedBytes = crypto.Decrypt(encryptedBytes); // Decrypt file bytes
File.WriteAllBytes(outputPath, decryptedBytes); // Write decrypted bytes to output file
Console.WriteLine($"EonaCat.Crypto: File decrypted: {outputPath}");
}
private static byte[] HkdfExpand(byte[] prk, byte[]? info, int outputLength)
{
const int hashLen = 64; // SHA512 output size in bytes
int n = (int)Math.Ceiling((double)outputLength / hashLen);
if (n > 255) throw new ArgumentOutOfRangeException(nameof(outputLength), "Output length too large");
byte[] okm = new byte[outputLength];
byte[] previousBlock = Array.Empty<byte>();
int offset = 0;
using (var hmac = new HMACSHA512Custom(prk))
{
for (byte i = 1; i <= n; i++)
{
// Build input = previousBlock || info || i
int inputLength = previousBlock.Length + (info?.Length ?? 0) + 1;
byte[] input = new byte[inputLength];
int pos = 0;
if (previousBlock.Length > 0)
{
Buffer.BlockCopy(previousBlock, 0, input, pos, previousBlock.Length);
pos += previousBlock.Length;
}
if (info != null && info.Length > 0)
{
Buffer.BlockCopy(info, 0, input, pos, info.Length);
pos += info.Length;
}
input[pos] = i;
// Compute HMAC
previousBlock = hmac.ComputeHash(input);
int toCopy = Math.Min(hashLen, outputLength - offset);
Array.Copy(previousBlock, 0, okm, offset, toCopy);
offset += toCopy;
}
}
// Clear sensitive buffer
Array.Clear(previousBlock, 0, previousBlock.Length);
return okm;
}
// --- HKDF Extract and Expand for Round Keys ---
private static byte[][] ExpandRoundKeysHKDF(byte[] masterKey, byte[] salt = null)
{
// Generate salt if none provided
if (salt == null || salt.Length != _keySize)
{
salt = new byte[_keySize];
salt = RandomNumberGeneratorCustom.ComputeHash(salt);
}
byte[] info = Encoding.UTF8.GetBytes("EonaCatCrypto round key");
byte[] prk;
using (var hmacExtract = new HMACSHA512Custom(salt))
{
prk = hmacExtract.ComputeHash(masterKey);
}
byte[][] roundKeys = new byte[_numRounds][];
using var hmacExpand = new HMACSHA512Custom(prk);
byte[] previous = Array.Empty<byte>();
for (int i = 0; i < _numRounds; i++)
{
byte[] input = new byte[previous.Length + info.Length + 1];
Buffer.BlockCopy(previous, 0, input, 0, previous.Length);
Buffer.BlockCopy(info, 0, input, previous.Length, info.Length);
input[^1] = (byte)(i + 1);
previous = hmacExpand.ComputeHash(input);
roundKeys[i] = new byte[_blockSize];
Array.Copy(previous, 0, roundKeys[i], 0, _blockSize);
}
// Zero out prk and previous for security
Array.Clear(prk, 0, prk.Length);
Array.Clear(previous, 0, previous.Length);
return roundKeys;
}
// --- HKDF Derive Separate HMAC Key ---
private static byte[] DeriveHmacKeyHKDF(byte[] masterKey, byte[] salt = null)
{
// Generate salt if none provided (64 bytes for SHA512 block size)
if (salt == null || salt.Length == 0)
{
salt = new byte[64];
salt = RandomNumberGeneratorCustom.ComputeHash(salt);
}
string signature = "Jeroen Saey - EonaCat";
string infoString = $"EonaCat Crypto HMAC Key - Signed by {signature}";
byte[] info = Encoding.UTF8.GetBytes(infoString);
byte[] prk;
using (var hmacExtract = new HMACSHA512Custom(salt))
{
prk = hmacExtract.ComputeHash(masterKey);
}
using var hmacExpand = new HMACSHA512Custom(prk);
byte[] input = new byte[info.Length + 1];
Buffer.BlockCopy(info, 0, input, 0, info.Length);
input[^1] = 1; // Counter byte
byte[] okm = hmacExpand.ComputeHash(input);
// Clear sensitive buffers
Array.Clear(prk, 0, prk.Length);
Array.Clear(input, 0, input.Length);
byte[] hmacKey = new byte[32];
Array.Copy(okm, 0, hmacKey, 0, 32);
Array.Clear(okm, 0, okm.Length);
return hmacKey;
}
// --- S-Box and Inverse S-Box ---
private static readonly byte[] SBox = new byte[256]
{
0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16
};
private static readonly byte[] InvSBox = new byte[256]
{
0x52,0x09,0x6a,0xd5,0x30,0x36,0xa5,0x38,0xbf,0x40,0xa3,0x9e,0x81,0xf3,0xd7,0xfb,
0x7c,0xe3,0x39,0x82,0x9b,0x2f,0xff,0x87,0x34,0x8e,0x43,0x44,0xc4,0xde,0xe9,0xcb,
0x54,0x7b,0x94,0x32,0xa6,0xc2,0x23,0x3d,0xee,0x4c,0x95,0x0b,0x42,0xfa,0xc3,0x4e,
0x08,0x2e,0xa1,0x66,0x28,0xd9,0x24,0xb2,0x76,0x5b,0xa2,0x49,0x6d,0x8b,0xd1,0x25,
0x72,0xf8,0xf6,0x64,0x86,0x68,0x98,0x16,0xd4,0xa4,0x5c,0xcc,0x5d,0x65,0xb6,0x92,
0x6c,0x70,0x48,0x50,0xfd,0xed,0xb9,0xda,0x5e,0x15,0x46,0x57,0xa7,0x8d,0x9d,0x84,
0x90,0xd8,0xab,0x00,0x8c,0xbc,0xd3,0x0a,0xf7,0xe4,0x58,0x05,0xb8,0xb3,0x45,0x06,
0xd0,0x2c,0x1e,0x8f,0xca,0x3f,0x0f,0x02,0xc1,0xaf,0xbd,0x03,0x01,0x13,0x8a,0x6b,
0x3a,0x91,0x11,0x41,0x4f,0x67,0xdc,0xea,0x97,0xf2,0xcf,0xce,0xf0,0xb4,0xe6,0x73,
0x96,0xac,0x74,0x22,0xe7,0xad,0x35,0x85,0xe2,0xf9,0x37,0xe8,0x1c,0x75,0xdf,0x6e,
0x47,0xf1,0x1a,0x71,0x1d,0x29,0xc5,0x89,0x6f,0xb7,0x62,0x0e,0xaa,0x18,0xbe,0x1b,
0xfc,0x56,0x3e,0x4b,0xc6,0xd2,0x79,0x20,0x9a,0xdb,0xc0,0xfe,0x78,0xcd,0x5a,0xf4,
0x1f,0xdd,0xa8,0x33,0x88,0x07,0xc7,0x31,0xb1,0x12,0x10,0x59,0x27,0x80,0xec,0x5f,
0x60,0x51,0x7f,0xa9,0x19,0xb5,0x4a,0x0d,0x2d,0xe5,0x7a,0x9f,0x93,0xc9,0x9c,0xef,
0xa0,0xe0,0x3b,0x4d,0xae,0x2a,0xf5,0xb0,0xc8,0xeb,0xbb,0x3c,0x83,0x53,0x99,0x61,
0x17,0x2b,0x04,0x7e,0xba,0x77,0xd6,0x26,0xe1,0x69,0x14,0x63,0x55,0x21,0x0c,0x7d
};
// --- GF(2^8) multiplication for MixColumns ---
private static byte GFMul(byte a, byte b)
{
byte p = 0;
for (int i = 0; i < 8; i++)
{
if ((b & 1) != 0)
{
p ^= a;
}
bool hiBitSet = (a & 0x80) != 0;
a <<= 1;
if (hiBitSet)
{
a ^= 0x1B;
}
b >>= 1;
}
return p;
}
// --- State transformations for encryption ---
private static void SubBytes(byte[] state)
{
for (int i = 0; i < state.Length; i++)
{
state[i] = SBox[state[i]];
}
}
private static void InvSubBytes(byte[] state)
{
for (int i = 0; i < state.Length; i++)
{
state[i] = InvSBox[state[i]];
}
}
private static void ShiftRows(byte[] state)
{
// 4x8 rows, each 8 bytes: AES style ShiftRows (similar)
// Shift rows by offsets 0,1,2,3
byte[] temp = new byte[_blockSize];
Array.Copy(state, temp, _blockSize);
for (int r = 0; r < 4; r++)
{
for (int c = 0; c < 8; c++)
{
state[r + 4 * c] = temp[r + 4 * ((c + r) % 8)];
}
}
}
private static void InvShiftRows(byte[] state)
{
byte[] temp = new byte[_blockSize];
Array.Copy(state, temp, _blockSize);
for (int r = 0; r < 4; r++)
{
for (int c = 0; c < 8; c++)
{
state[r + 4 * c] = temp[r + 4 * ((c + 8 - r) % 8)];
}
}
}
private static void MixColumns(byte[] state)
{
for (int c = 0; c < 8; c++)
{
int i = c * 4;
byte s0 = state[i];
byte s1 = state[i + 1];
byte s2 = state[i + 2];
byte s3 = state[i + 3];
byte t0 = (byte)(GFMul(s0, 2) ^ GFMul(s1, 3) ^ s2 ^ s3);
byte t1 = (byte)(s0 ^ GFMul(s1, 2) ^ GFMul(s2, 3) ^ s3);
byte t2 = (byte)(s0 ^ s1 ^ GFMul(s2, 2) ^ GFMul(s3, 3));
byte t3 = (byte)(GFMul(s0, 3) ^ s1 ^ s2 ^ GFMul(s3, 2));
state[i] = t0;
state[i + 1] = t1;
state[i + 2] = t2;
state[i + 3] = t3;
}
}
private static void InvMixColumns(byte[] state)
{
for (int c = 0; c < 8; c++)
{
int i = c * 4;
byte s0 = state[i];
byte s1 = state[i + 1];
byte s2 = state[i + 2];
byte s3 = state[i + 3];
byte t0 = (byte)(GFMul(s0, 0x0e) ^ GFMul(s1, 0x0b) ^ GFMul(s2, 0x0d) ^ GFMul(s3, 0x09));
byte t1 = (byte)(GFMul(s0, 0x09) ^ GFMul(s1, 0x0e) ^ GFMul(s2, 0x0b) ^ GFMul(s3, 0x0d));
byte t2 = (byte)(GFMul(s0, 0x0d) ^ GFMul(s1, 0x09) ^ GFMul(s2, 0x0e) ^ GFMul(s3, 0x0b));
byte t3 = (byte)(GFMul(s0, 0x0b) ^ GFMul(s1, 0x0d) ^ GFMul(s2, 0x09) ^ GFMul(s3, 0x0e));
state[i] = t0;
state[i + 1] = t1;
state[i + 2] = t2;
state[i + 3] = t3;
}
}
// --- AddRoundKey ---
private static void AddRoundKey(byte[] state, byte[] roundKey)
{
for (int i = 0; i < _blockSize; i++)
{
state[i] ^= roundKey[i];
}
}
// --- Block Encryption ---
public byte[] EncryptBlock(byte[] block)
{
if (block.Length != _blockSize)
{
throw new ArgumentException($"EonaCat.Crypto: Block size must be {_blockSize} bytes");
}
byte[] state = new byte[_blockSize];
Array.Copy(block, state, _blockSize);
AddRoundKey(state, _roundKeys[0]);
for (int round = 1; round < _numRounds; round++)
{
SubBytes(state);
ShiftRows(state);
MixColumns(state);
AddRoundKey(state, _roundKeys[round]);
}
SubBytes(state);
ShiftRows(state);
AddRoundKey(state, _roundKeys[_numRounds - 1]); // final round key (reused last key)
return state;
}
// --- Block Decryption ---
public byte[] DecryptBlock(byte[] block)
{
if (block.Length != _blockSize)
{
throw new ArgumentException($"EonaCat.Crypto: Block size must be {_blockSize} bytes");
}
byte[] state = new byte[_blockSize];
Array.Copy(block, state, _blockSize);
AddRoundKey(state, _roundKeys[_numRounds - 1]);
InvShiftRows(state);
InvSubBytes(state);
for (int round = _numRounds - 2; round >= 0; round--)
{
AddRoundKey(state, _roundKeys[round]);
InvMixColumns(state);
InvShiftRows(state);
InvSubBytes(state);
}
AddRoundKey(state, _roundKeys[0]);
return state;
}
// --- CTR Mode Encryption/Decryption (same for both) ---
private byte[] EncryptCTR(byte[] input, byte[] nonce)
{
if (nonce == null || nonce.Length != _nonceSize)
{
throw new ArgumentException($"EonaCat.Crypto: Nonce must be {_nonceSize} bytes");
}
byte[] output = new byte[input.Length];
int blocks = (input.Length + _blockSize - 1) / _blockSize;
for (int i = 0; i < blocks; i++)
{
byte[] counterBlock = new byte[_blockSize];
Array.Copy(nonce, 0, counterBlock, 0, _nonceSize);
// Counter big endian
int ctr = i;
counterBlock[_nonceSize + 0] = (byte)(ctr >> 24 & 0xFF);
counterBlock[_nonceSize + 1] = (byte)(ctr >> 16 & 0xFF);
counterBlock[_nonceSize + 2] = (byte)(ctr >> 8 & 0xFF);
counterBlock[_nonceSize + 3] = (byte)(ctr & 0xFF);
byte[] keystream = EncryptBlock(counterBlock);
int blockSize = Math.Min(_blockSize, input.Length - i * _blockSize);
for (int j = 0; j < blockSize; j++)
{
output[i * _blockSize + j] = (byte)(input[i * _blockSize + j] ^ keystream[j]);
}
}
return output;
}
// --- Public Encrypt method ---
public byte[] Encrypt(byte[] plaintext)
{
if (plaintext == null)
{
throw new ArgumentNullException(nameof(plaintext));
}
byte[] nonce = new byte[_nonceSize];
RandomNumberGeneratorCustom.ComputeHash(nonce);
byte[] ciphertext = EncryptCTR(plaintext, nonce);
// Authenticated data = nonce + length(4 bytes) + ciphertext
byte[] lengthBytes = BitConverter.GetBytes(plaintext.Length);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(lengthBytes);
}
byte[] dataToAuthenticate = new byte[_nonceSize + 4 + ciphertext.Length];
Buffer.BlockCopy(nonce, 0, dataToAuthenticate, 0, _nonceSize);
Buffer.BlockCopy(lengthBytes, 0, dataToAuthenticate, _nonceSize, 4);
Buffer.BlockCopy(ciphertext, 0, dataToAuthenticate, _nonceSize + 4, ciphertext.Length);
byte[] tag;
using (var hmac = new HMACSHA256Custom(_hmacKey))
{
tag = hmac.ComputeHash(dataToAuthenticate);
}
byte[] result = new byte[dataToAuthenticate.Length + _tagSize];
Buffer.BlockCopy(dataToAuthenticate, 0, result, 0, dataToAuthenticate.Length);
Buffer.BlockCopy(tag, 0, result, dataToAuthenticate.Length, _tagSize);
// Convert encrypted data to Base64 string
string base64 = Convert.ToBase64String(result);
// Prepare the final output: FileIdentifier + Base64 string
string fullString = _fileIdentifier + base64;
// Return UTF8 bytes of full string (identifier + base64)
return Encoding.UTF8.GetBytes(fullString);
}
// --- Public Decrypt method ---
public byte[] Decrypt(byte[] fileBytes)
{
if (fileBytes == null || fileBytes.Length == 0)
{
throw new ArgumentNullException(nameof(fileBytes));
}
// Convert bytes to string
string fullString = Encoding.UTF8.GetString(fileBytes);
// Check for file identifier at start
if (!fullString.StartsWith(_fileIdentifier))
{
throw new Exception("EonaCat.Crypto: Invalid file format: missing file identifier");
}
// Remove the file identifier prefix
string base64 = fullString.Substring(_fileIdentifier.Length);
// Decode Base64 to encrypted data bytes
byte[] ciphertextWithTag = Convert.FromBase64String(base64);
if (ciphertextWithTag.Length < _nonceSize + 4 + _tagSize)
{
throw new ArgumentException("EonaCat.Crypto: Ciphertext too short");
}
int authDataLen = ciphertextWithTag.Length - _tagSize;
byte[] tag = new byte[_tagSize];
byte[] authData = new byte[authDataLen];
Buffer.BlockCopy(ciphertextWithTag, authDataLen, tag, 0, _tagSize);
Buffer.BlockCopy(ciphertextWithTag, 0, authData, 0, authDataLen);
byte[] computedTag;
using (var hmac = new HMACSHA256Custom(_hmacKey))
{
computedTag = hmac.ComputeHash(authData);
}
if (!ConstantTimeEquals(computedTag, tag))
{
throw new Exception("EonaCat.Crypto: Authentication failed (tag mismatch)");
}
// Extract nonce and length
byte[] nonce = new byte[_nonceSize];
Buffer.BlockCopy(authData, 0, nonce, 0, _nonceSize);
byte[] lengthBytes = new byte[4];
Buffer.BlockCopy(authData, _nonceSize, lengthBytes, 0, 4);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(lengthBytes);
}
int plaintextLength = BitConverter.ToInt32(lengthBytes, 0);
if (plaintextLength < 0 || plaintextLength > authDataLen - _nonceSize - 4)
{
throw new Exception("EonaCat.Crypto: Invalid plaintext length");
}
byte[] ciphertext = new byte[authDataLen - _nonceSize - 4];
Buffer.BlockCopy(authData, _nonceSize + 4, ciphertext, 0, ciphertext.Length);
byte[] plaintext = EncryptCTR(ciphertext, nonce);
if (plaintext.Length != plaintextLength)
{
throw new Exception("EonaCat.Crypto: Plaintext length mismatch");
}
return plaintext;
}
private static bool ConstantTimeEquals(byte[] a, byte[] b)
{
if (a.Length != b.Length)
{
return false;
}
int result = 0;
for (int i = 0; i < a.Length; i++)
{
result |= a[i] ^ b[i];
}
return result == 0;
}
}
}

View File

@ -0,0 +1,90 @@
namespace EonaCat.Crypto.Hashing
{
internal class HMACSHA256Custom : IDisposable
{
private const int _blockSize = 64; // SHA256 block size in bytes
private readonly byte[] _key;
private readonly byte[] _opad;
private readonly byte[] _ipad;
private bool disposed = false;
public HMACSHA256Custom(byte[] key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (key.Length > _blockSize)
{
key = SHA256Custom.ComputeHash(key);
}
this._key = new byte[_blockSize];
Array.Copy(key, this._key, key.Length);
_ipad = new byte[_blockSize];
_opad = new byte[_blockSize];
for (int i = 0; i < _blockSize; i++)
{
_ipad[i] = (byte)(this._key[i] ^ 0x36);
_opad[i] = (byte)(this._key[i] ^ 0x5c);
}
}
public byte[] ComputeHash(byte[] message)
{
if (disposed)
{
throw new ObjectDisposedException(nameof(HMACSHA256Custom));
}
byte[] innerInput = new byte[_ipad.Length + message.Length];
Array.Copy(_ipad, 0, innerInput, 0, _ipad.Length);
Array.Copy(message, 0, innerInput, _ipad.Length, message.Length);
byte[] innerHash = SHA256Custom.ComputeHash(innerInput);
byte[] outerInput = new byte[_opad.Length + innerHash.Length];
Array.Copy(_opad, 0, outerInput, 0, _opad.Length);
Array.Copy(innerHash, 0, outerInput, _opad.Length, innerHash.Length);
return SHA256Custom.ComputeHash(outerInput);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
if (_key != null)
{
Array.Clear(_key, 0, _key.Length);
}
if (_ipad != null)
{
Array.Clear(_ipad, 0, _ipad.Length);
}
if (_opad != null)
{
Array.Clear(_opad, 0, _opad.Length);
}
}
disposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}

View File

@ -0,0 +1,88 @@
internal class HMACSHA512Custom : IDisposable
{
private const int _blockSize = 128; // SHA512 block size in bytes
private readonly byte[] _key;
private readonly byte[] _opad;
private readonly byte[] _ipad;
private bool _isDisposed = false;
public HMACSHA512Custom(byte[] key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (key.Length > _blockSize)
{
key = SHA512Custom.ComputeHash(key);
}
this._key = new byte[_blockSize];
Array.Copy(key, this._key, key.Length);
_ipad = new byte[_blockSize];
_opad = new byte[_blockSize];
for (int i = 0; i < _blockSize; i++)
{
_ipad[i] = (byte)(this._key[i] ^ 0x36);
_opad[i] = (byte)(this._key[i] ^ 0x5c);
}
}
public byte[] ComputeHash(byte[] message)
{
if (_isDisposed)
{
throw new ObjectDisposedException(nameof(HMACSHA512Custom));
}
byte[] innerInput = new byte[_ipad.Length + message.Length];
Array.Copy(_ipad, 0, innerInput, 0, _ipad.Length);
Array.Copy(message, 0, innerInput, _ipad.Length, message.Length);
byte[] innerHash = SHA512Custom.ComputeHash(innerInput);
byte[] outerInput = new byte[_opad.Length + innerHash.Length];
Array.Copy(_opad, 0, outerInput, 0, _opad.Length);
Array.Copy(innerHash, 0, outerInput, _opad.Length, innerHash.Length);
return SHA512Custom.ComputeHash(outerInput);
}
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
// Clear sensitive data in memory
if (_key != null)
{
Array.Clear(_key, 0, _key.Length);
}
if (_ipad != null)
{
Array.Clear(_ipad, 0, _ipad.Length);
}
if (_opad != null)
{
Array.Clear(_opad, 0, _opad.Length);
}
}
_isDisposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}

View File

@ -0,0 +1,154 @@
internal static class SHA256Custom
{
// SHA-256 constants (first 32 bits of the fractional parts of the cube roots of the first 64 primes)
private static readonly uint[] _k = new uint[]
{
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
// Initial hash values (first 32 bits of the fractional parts of the square roots of the first 8 primes)
private static readonly uint[] _h0 = new uint[]
{
0x6a09e667,
0xbb67ae85,
0x3c6ef372,
0xa54ff53a,
0x510e527f,
0x9b05688c,
0x1f83d9ab,
0x5be0cd19
};
public static byte[] ComputeHash(byte[] data)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
// 1. Pre-processing (Padding)
byte[] padded = Pad(data);
// 2. Initialize hash values
uint[] H = new uint[8];
Array.Copy(_h0, H, 8);
// 3. Process the message in successive 512-bit chunks (64 bytes)
int blockCount = padded.Length / 64;
for (int i = 0; i < blockCount; i++)
{
uint[] W = new uint[64];
// Copy chunk into first 16 words W[0..15] as big-endian
for (int t = 0; t < 16; t++)
{
int index = (i * 64) + (t * 4);
W[t] = (uint)(padded[index] << 24 | padded[index + 1] << 16 | padded[index + 2] << 8 | padded[index + 3]);
}
// Extend the first 16 words into the remaining 48 words W[16..63]
for (int t = 16; t < 64; t++)
{
uint s0 = RotateRight(W[t - 15], 7) ^ RotateRight(W[t - 15], 18) ^ (W[t - 15] >> 3);
uint s1 = RotateRight(W[t - 2], 17) ^ RotateRight(W[t - 2], 19) ^ (W[t - 2] >> 10);
W[t] = W[t - 16] + s0 + W[t - 7] + s1;
}
// Initialize working variables a,b,c,d,e,f,g,h with current hash value
uint a = H[0];
uint b = H[1];
uint c = H[2];
uint d = H[3];
uint e = H[4];
uint f = H[5];
uint g = H[6];
uint h = H[7];
// Main compression function
for (int t = 0; t < 64; t++)
{
uint S1 = RotateRight(e, 6) ^ RotateRight(e, 11) ^ RotateRight(e, 25);
uint ch = (e & f) ^ (~e & g);
uint temp1 = h + S1 + ch + _k[t] + W[t];
uint S0 = RotateRight(a, 2) ^ RotateRight(a, 13) ^ RotateRight(a, 22);
uint maj = (a & b) ^ (a & c) ^ (b & c);
uint temp2 = S0 + maj;
h = g;
g = f;
f = e;
e = d + temp1;
d = c;
c = b;
b = a;
a = temp1 + temp2;
}
// Add the compressed chunk to the current hash value
H[0] += a;
H[1] += b;
H[2] += c;
H[3] += d;
H[4] += e;
H[5] += f;
H[6] += g;
H[7] += h;
}
// 4. Produce the final hash value (big-endian)
byte[] hash = new byte[32];
for (int i = 0; i < 8; i++)
{
hash[i * 4] = (byte)((H[i] >> 24) & 0xff);
hash[i * 4 + 1] = (byte)((H[i] >> 16) & 0xff);
hash[i * 4 + 2] = (byte)((H[i] >> 8) & 0xff);
hash[i * 4 + 3] = (byte)(H[i] & 0xff);
}
return hash;
}
private static byte[] Pad(byte[] data)
{
ulong bitLen = (ulong)data.Length * 8;
// Padding: append '1' bit then zero bits until message length ≡ 448 mod 512
int padLen = 64 - (int)((data.Length + 8) % 64);
if (padLen == 0)
{
padLen = 64;
}
byte[] padded = new byte[data.Length + padLen + 8];
Array.Copy(data, padded, data.Length);
padded[data.Length] = 0x80; // append '1' bit
// Append length as 64-bit big-endian
for (int i = 0; i < 8; i++)
{
padded[padded.Length - 1 - i] = (byte)((bitLen >> (8 * i)) & 0xff);
}
return padded;
}
private static uint RotateRight(uint x, int n)
{
return (x >> n) | (x << (32 - n));
}
}

View File

@ -0,0 +1,168 @@
using System.Text;
internal class SHA512Custom
{
// Constants as per SHA512 spec
private static readonly ulong[] _k = new ulong[]
{
0x428a2f98d728ae22UL, 0x7137449123ef65cdUL, 0xb5c0fbcfec4d3b2fUL, 0xe9b5dba58189dbbcUL,
0x3956c25bf348b538UL, 0x59f111f1b605d019UL, 0x923f82a4af194f9bUL, 0xab1c5ed5da6d8118UL,
0xd807aa98a3030242UL, 0x12835b0145706fbeUL, 0x243185be4ee4b28cUL, 0x550c7dc3d5ffb4e2UL,
0x72be5d74f27b896fUL, 0x80deb1fe3b1696b1UL, 0x9bdc06a725c71235UL, 0xc19bf174cf692694UL,
0xe49b69c19ef14ad2UL, 0xefbe4786384f25e3UL, 0x0fc19dc68b8cd5b5UL, 0x240ca1cc77ac9c65UL,
0x2de92c6f592b0275UL, 0x4a7484aa6ea6e483UL, 0x5cb0a9dcbd41fbd4UL, 0x76f988da831153b5UL,
0x983e5152ee66dfabUL, 0xa831c66d2db43210UL, 0xb00327c898fb213fUL, 0xbf597fc7beef0ee4UL,
0xc6e00bf33da88fc2UL, 0xd5a79147930aa725UL, 0x06ca6351e003826fUL, 0x142929670a0e6e70UL,
0x27b70a8546d22ffcUL, 0x2e1b21385c26c926UL, 0x4d2c6dfc5ac42aedUL, 0x53380d139d95b3dfUL,
0x650a73548baf63deUL, 0x766a0abb3c77b2a8UL, 0x81c2c92e47edaee6UL, 0x92722c851482353bUL,
0xa2bfe8a14cf10364UL, 0xa81a664bbc423001UL, 0xc24b8b70d0f89791UL, 0xc76c51a30654be30UL,
0xd192e819d6ef5218UL, 0xd69906245565a910UL, 0xf40e35855771202aUL, 0x106aa07032bbd1b8UL,
0x19a4c116b8d2d0c8UL, 0x1e376c085141ab53UL, 0x2748774cdf8eeb99UL, 0x34b0bcb5e19b48a8UL,
0x391c0cb3c5c95a63UL, 0x4ed8aa4ae3418acbUL, 0x5b9cca4f7763e373UL, 0x682e6ff3d6b2b8a3UL,
0x748f82ee5defb2fcUL, 0x78a5636f43172f60UL, 0x84c87814a1f0ab72UL, 0x8cc702081a6439ecUL,
0x90befffa23631e28UL, 0xa4506cebde82bde9UL, 0xbef9a3f7b2c67915UL, 0xc67178f2e372532bUL,
0xca273eceea26619cUL, 0xd186b8c721c0c207UL, 0xeada7dd6cde0eb1eUL, 0xf57d4f7fee6ed178UL,
0x06f067aa72176fbaUL, 0x0a637dc5a2c898a6UL, 0x113f9804bef90daeUL, 0x1b710b35131c471bUL,
0x28db77f523047d84UL, 0x32caab7b40c72493UL, 0x3c9ebe0a15c9bebcUL, 0x431d67c49c100d4cUL,
0x4cc5d4becb3e42b6UL, 0x597f299cfc657e2aUL, 0x5fcb6fab3ad6faecUL, 0x6c44198c4a475817UL
};
private static ulong ROTR(ulong x, int n) => (x >> n) | (x << (64 - n));
private static ulong SHR(ulong x, int n) => x >> n;
private static ulong Ch(ulong x, ulong y, ulong z) => (x & y) ^ (~x & z);
private static ulong Maj(ulong x, ulong y, ulong z) => (x & y) ^ (x & z) ^ (y & z);
private static ulong Sigma0(ulong x) => ROTR(x, 28) ^ ROTR(x, 34) ^ ROTR(x, 39);
private static ulong Sigma1(ulong x) => ROTR(x, 14) ^ ROTR(x, 18) ^ ROTR(x, 41);
private static ulong sigma0(ulong x) => ROTR(x, 1) ^ ROTR(x, 8) ^ SHR(x, 7);
private static ulong sigma1(ulong x) => ROTR(x, 19) ^ ROTR(x, 61) ^ SHR(x, 6);
private static byte[] PadMessage(byte[] message)
{
ulong bitLength = (ulong)message.Length * 8;
// Padding: append 0x80, then 0x00 bytes until length mod 128 == 112
int paddingLength = 128 - (int)((message.Length + 16) % 128);
if (paddingLength == 0)
{
paddingLength = 128;
}
byte[] padded = new byte[message.Length + paddingLength + 16];
Array.Copy(message, padded, message.Length);
padded[message.Length] = 0x80;
// Last 16 bytes = length in bits, big-endian
for (int i = 0; i < 16; i++)
{
padded[padded.Length - 1 - i] = (byte)((bitLength >> (8 * i)) & 0xFF);
}
return padded;
}
public static byte[] ComputeHash(byte[] message)
{
// Initial Hash Values (H0-H7) as per SHA512 spec
ulong[] H = new ulong[]
{
0x6a09e667f3bcc908UL,
0xbb67ae8584caa73bUL,
0x3c6ef372fe94f82bUL,
0xa54ff53a5f1d36f1UL,
0x510e527fade682d1UL,
0x9b05688c2b3e6c1fUL,
0x1f83d9abfb41bd6bUL,
0x5be0cd19137e2179UL
};
byte[] padded = PadMessage(message);
ulong[] W = new ulong[80];
for (int chunkIndex = 0; chunkIndex < padded.Length / 128; chunkIndex++)
{
// Prepare message schedule W
for (int t = 0; t < 16; t++)
{
int start = chunkIndex * 128 + t * 8;
W[t] = ((ulong)padded[start] << 56)
| ((ulong)padded[start + 1] << 48)
| ((ulong)padded[start + 2] << 40)
| ((ulong)padded[start + 3] << 32)
| ((ulong)padded[start + 4] << 24)
| ((ulong)padded[start + 5] << 16)
| ((ulong)padded[start + 6] << 8)
| ((ulong)padded[start + 7]);
}
for (int t = 16; t < 80; t++)
{
W[t] = sigma1(W[t - 2]) + W[t - 7] + sigma0(W[t - 15]) + W[t - 16];
}
// Initialize working vars
ulong a = H[0];
ulong b = H[1];
ulong c = H[2];
ulong d = H[3];
ulong e = H[4];
ulong f = H[5];
ulong g = H[6];
ulong h = H[7];
// Main loop
for (int t = 0; t < 80; t++)
{
ulong T1 = h + Sigma1(e) + Ch(e, f, g) + _k[t] + W[t];
ulong T2 = Sigma0(a) + Maj(a, b, c);
h = g;
g = f;
f = e;
e = d + T1;
d = c;
c = b;
b = a;
a = T1 + T2;
}
// Compute intermediate hash value
H[0] += a;
H[1] += b;
H[2] += c;
H[3] += d;
H[4] += e;
H[5] += f;
H[6] += g;
H[7] += h;
}
// Convert hash to byte array (big endian)
byte[] hash = new byte[64];
for (int i = 0; i < 8; i++)
{
hash[i * 8 + 0] = (byte)(H[i] >> 56);
hash[i * 8 + 1] = (byte)(H[i] >> 48);
hash[i * 8 + 2] = (byte)(H[i] >> 40);
hash[i * 8 + 3] = (byte)(H[i] >> 32);
hash[i * 8 + 4] = (byte)(H[i] >> 24);
hash[i * 8 + 5] = (byte)(H[i] >> 16);
hash[i * 8 + 6] = (byte)(H[i] >> 8);
hash[i * 8 + 7] = (byte)(H[i]);
}
return hash;
}
public static string ToHexString(byte[] data)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (byte currentByte in data)
{
stringBuilder.AppendFormat("{0:x2}", currentByte);
}
return stringBuilder.ToString();
}
}

View File

@ -0,0 +1,44 @@
namespace EonaCat.Crypto.Helpers
{
public static class RandomNumberGeneratorCustom
{
// Generate a pseudo-random 32-byte output based on the input nonce
public static byte[] ComputeHash(byte[] nonce)
{
if (nonce == null)
{
throw new ArgumentNullException(nameof(nonce));
}
// Internal state seed = nonce padded/truncated to 32 bytes
byte[] state = new byte[32];
int len = Math.Min(nonce.Length, 32);
Array.Copy(nonce, state, len);
if (len < 32)
{
for (int i = len; i < 32; i++)
{
state[i] = 0;
}
}
ulong counter = 0;
// Prepare input = state || counter (8 bytes)
byte[] input = new byte[40]; // 32 + 8
Array.Copy(state, input, 32);
// Append counter in big endian
for (int i = 0; i < 8; i++)
{
input[39 - i] = (byte)(counter >> 8 * i & 0xFF);
}
// Compute hash output using your custom SHA256 implementation
byte[] output = SHA256Custom.ComputeHash(input);
return output;
}
}
}

87
EonaCat.Crypto/Program.cs Normal file
View File

@ -0,0 +1,87 @@
using System.Text;
using EonaCat.Crypto;
using EonaCat.Crypto.Helpers;
class Program
{
static void Main()
{
// Generate a random 128-byte (1024-bit) key
byte[] key = new byte[128];
RandomNumberGeneratorCustom.ComputeHash(key);
var crypto = new EonaCatCrypto("WERKT DIT GEWOON?");
//var crypto = new EonaCatCrypto(key);
string longLoremIpsum = @"
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua!
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur?
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.
Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.
Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur?
Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.
Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.
Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae.
Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
Special characters test: !@#$%^&*()_+-=[]{}|;':\"",./<>?`~
Unicode symbols: © ® £ ¥ µ π Ω α β γ δ ε ζ η θ 𝜃 λ µ ν ξ π ρ σ τ φ χ ψ ω
Accents and diacritics: à á â ã ä å æ ç è é ê ë ì í î ï ñ ò ó ô õ ö ø ù ú û ü ý ÿ
Quotes and dashes:
End of test string.
";
Console.WriteLine("Original text length: " + longLoremIpsum.Length);
byte[] plaintext = Encoding.UTF8.GetBytes(longLoremIpsum);
// Encrypt text
byte[] encrypted = crypto.Encrypt(plaintext);
Console.WriteLine("Encrypted (base64): " + Convert.ToBase64String(encrypted));
// Decrypt text
var crypto2 = new EonaCatCrypto("WERKT DIT GEWOON?");
byte[] decrypted = crypto2.Decrypt(encrypted);
string decryptedText = Encoding.UTF8.GetString(decrypted);
Console.WriteLine("Decrypted text length: " + decryptedText.Length);
if (longLoremIpsum == decryptedText)
{
Console.WriteLine("SUCCESS: Decrypted text matches original!");
}
else
{
Console.WriteLine("FAILURE: Decrypted text does NOT match original!");
}
// Example file paths
string inputFilePath = "Malenia.mp3";
string encryptedFilePath = "Malenia.mp3.dat";
string decryptedFilePath = "Malenia_decrypted.mp3";
if (!File.Exists(inputFilePath))
{
inputFilePath = "EonaCat.Crypto.SampleFile.txt";
// Create a sample file if it doesn't exist
File.WriteAllText(inputFilePath, longLoremIpsum);
Console.WriteLine($"Sample file created: {inputFilePath}");
}
// Encrypt file
EonaCatCrypto.EncryptFile(inputFilePath, encryptedFilePath, crypto);
// Decrypt file
EonaCatCrypto.DecryptFile(encryptedFilePath, decryptedFilePath, crypto);
Console.WriteLine("File encryption and decryption completed.");
}
}

213
LICENSE
View File

@ -1,73 +1,204 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
https://EonaCat.com/license/
1. Definitions.
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
OF SOFTWARE BY EONACAT (JEROEN SAEY)
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
1. Definitions.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
END OF TERMS AND CONDITIONS
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
APPENDIX: How to apply the Apache License to your work.
END OF TERMS AND CONDITIONS
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
APPENDIX: How to apply the Apache License to your work.
Copyright 2025 EonaCat
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Copyright [yyyy] [name of copyright owner]
http://www.apache.org/licenses/LICENSE-2.0
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

206
README.md
View File

@ -1,3 +1,205 @@
# EonaCat.Crypto
EonaCat.Crypto
# EonaCatCrypto
EonaCatCrypto is a cryptographic library for key derivation and symmetric encryption, using HKDF-SHA512 for secure key expansion and HMAC for authentication.
---
## Features
- Derives fixed-length keys from arbitrary string or byte array inputs using HKDF-SHA512
- Domain-separated keys for encryption rounds and HMAC authentication
- Securely clears sensitive data from memory after use
- Easy to use constructors accepting both string and byte[] keys
- Encrypt strings, byte arrays and files
* Optionally: a salt can be provided via the constructor (if not provided a random salt is used)
---
## Usage
### Initialize with a string key
#### Encrypt:
```csharp
string userKey = "my secure password";
var crypto = new EonaCatCrypto(userKey);
var payload = "THIS IS MY SECURE TEXT";
byte[] plaintext = Encoding.UTF8.GetBytes(payload);
// Encrypt text
byte[] encrypted = crypto.Encrypt(plaintext);
Console.WriteLine("Encrypted (base64): " + Convert.ToBase64String(encrypted));
```
#### Decrypt:
```csharp
string userKey = "my secure password";
var crypto = new EonaCatCrypto(userKey);
byte[] decrypted = crypto.Decrypt(encrypted);
string decryptedText = Encoding.UTF8.GetString(decrypted);
Console.WriteLine("Decrypted text length: " + decryptedText.Length);
```
#### Check if valid:
```csharp
if (payload == decryptedText)
{
Console.WriteLine("SUCCESS: Decrypted text matches original!");
}
else
{
Console.WriteLine("FAILURE: Decrypted text does NOT match original!");
}
```
### Initialize with a byte[] key
#### Encrypt:
```csharp
// Generate a random 128-bytes (1024-bit) key
byte[] key = new byte[128];
RandomNumberGeneratorCustom.ComputeHash(key);
// Example for key saving:
File.WriteAllBytes(key, "key.bin");
var crypto = new EonaCatCrypto(key);
var payload = "THIS IS MY SECURE TEXT";
byte[] plaintext = Encoding.UTF8.GetBytes(payload);
// Encrypt text
byte[] encrypted = crypto.Encrypt(plaintext);
Console.WriteLine("Encrypted (base64): " + Convert.ToBase64String(encrypted));
```
#### Decrypt:
```csharp
byte[] key = "YOUR 128-bytes (1024-bit) KEY ARRAY";
// For example:
byte[] key = File.ReadAllBytes("key.bin");
var crypto = new EonaCatCrypto(userKey);
byte[] decrypted = crypto.Decrypt(encrypted);
string decryptedText = Encoding.UTF8.GetString(decrypted);
Console.WriteLine("Decrypted text length: " + decryptedText.Length);
```
#### Check if valid:
```csharp
if (payload == decryptedText)
{
Console.WriteLine("SUCCESS: Decrypted text matches original!");
}
else
{
Console.WriteLine("FAILURE: Decrypted text does NOT match original!");
}
```
## Encrypt a file:
```csharp
EonaCatCrypto.EncryptFile(inputFilePath, encryptedFilePath, crypto)
```
## Decrypt a file:
```csharp
EonaCatCrypto.DecryptFile(encryptedFilePath, decryptedFilePath, crypto);
```
## Full example:
```csharp
using System.Text;
using EonaCat.Crypto;
using EonaCat.Crypto.Helpers;
class Program
{
static void Main()
{
// Generate a random 128-byte (1024-bit) key
byte[] key = new byte[128];
RandomNumberGeneratorCustom.ComputeHash(key);
var crypto = new EonaCatCrypto("WERKT DIT GEWOON?");
//var crypto = new EonaCatCrypto(key);
string longLoremIpsum = @"
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua!
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur?
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.
Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.
Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur?
Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.
Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.
Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae.
Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
Special characters test: !@#$%^&*()_+-=[]{}|;':\"",./<>?`~
Unicode symbols: © ® ™ € £ ¥ ∞ ≈ ≠ ≤ ≥ µ ∑ π √ ∫ ∂ ∆ ∇ Ω α β γ δ ε ζ η θ 𝜃 λ µ ν ξ π ρ σ τ φ χ ψ ω
Accents and diacritics: à á â ã ä å æ ç è é ê ë ì í î ï ñ ò ó ô õ ö ø ù ú û ü ý ÿ
Quotes and dashes: “ ”
End of test string.
";
Console.WriteLine("Original text length: " + longLoremIpsum.Length);
byte[] plaintext = Encoding.UTF8.GetBytes(longLoremIpsum);
// Encrypt text
byte[] encrypted = crypto.Encrypt(plaintext);
Console.WriteLine("Encrypted (base64): " + Convert.ToBase64String(encrypted));
// Decrypt text
var crypto2 = new EonaCatCrypto("WERKT DIT GEWOON?");
byte[] decrypted = crypto2.Decrypt(encrypted);
string decryptedText = Encoding.UTF8.GetString(decrypted);
Console.WriteLine("Decrypted text length: " + decryptedText.Length);
if (longLoremIpsum == decryptedText)
{
Console.WriteLine("SUCCESS: Decrypted text matches original!");
}
else
{
Console.WriteLine("FAILURE: Decrypted text does NOT match original!");
}
// Example file paths
string inputFilePath = "Malenia.mp3";
string encryptedFilePath = "Malenia.mp3.dat";
string decryptedFilePath = "Malenia_decrypted.mp3";
if (!File.Exists(inputFilePath))
{
inputFilePath = "EonaCat.Crypto.SampleFile.txt";
// Create a sample file if it doesn't exist
File.WriteAllText(inputFilePath, longLoremIpsum);
Console.WriteLine($"Sample file created: {inputFilePath}");
}
// Encrypt file
EonaCatCrypto.EncryptFile(inputFilePath, encryptedFilePath, crypto);
// Decrypt file
EonaCatCrypto.DecryptFile(encryptedFilePath, decryptedFilePath, crypto);
Console.WriteLine("File encryption and decryption completed.");
}
}
```

BIN
icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB