EonaCat.Security
1.1.0
Prefix Reserved
dotnet add package EonaCat.Security --version 1.1.0
NuGet\Install-Package EonaCat.Security -Version 1.1.0
<PackageReference Include="EonaCat.Security" Version="1.1.0" />
<PackageVersion Include="EonaCat.Security" Version="1.1.0" />
<PackageReference Include="EonaCat.Security" />
paket add EonaCat.Security --version 1.1.0
#r "nuget: EonaCat.Security, 1.1.0"
#:package EonaCat.Security@1.1.0
#addin nuget:?package=EonaCat.Security&version=1.1.0
#tool nuget:?package=EonaCat.Security&version=1.1.0
EonaCat Security
Security library for .NET Framework 4.8.1, .NET Standard 2.1, .NET 5/6/7/8/9.
Features
| Feature | Description |
|---|---|
| Secrets Manager | Securely load/save encrypted key-value pairs from file or memory |
| AntiDebugger | Detect and respond to debugging tools, network monitors, and disassemblers |
| AntiDump | Corrupt PE headers at runtime to prevent memory dumping |
| Bytes Generator | Generate random bytes and derive bytes from passwords |
| Data Compressor | Compress and decompress data |
| Data Encryptor | Encrypt/decrypt objects using AES-256 |
| File Encryptor | Encrypt/decrypt files on disk |
| Hash Computer | Compute and verify cryptographic hashes |
| Password Validator | Validate password strength with configurable rules |
| Input Sanitizer | Prevent injection attacks by sanitizing strings |
| Rate Limiter | Prevent brute-force attacks with lockout periods |
| Secure Key Derivation | Derive encryption keys from passwords using PBKDF2-HMAC-SHA512 |
| Secret Masker | Redact secrets from logs and error messages |
| Secure Configuration Provider | Store secrets encrypted at rest in config files |
| Sensitive Data Guard | Detect plain-text secrets (AWS keys, tokens, etc.) in strings |
| Audit Logger | Tamper-evident HMAC-chained audit logging |
| Safe Vault | Encrypted item storage with HMAC integrity verification |
| Secure Credential Store | Encrypt/decrypt credentials using AES-GCM |
| Environment Variable Manager | Securely manage environment variables with optional encryption |
| TOTP Manager | Generate time-based one-time passwords for 2FA |
| User Manager | User account management with secure password hashing and rate limiting |
| Secure Client/Server | TLS-secured client/server communication with mutual authentication |
| File Sharing Manager | Encrypt files for specific users using per-user keys |
| Passwordless Authenticator | Cross-platform passwordless login using ECDSA challenge-response (FIDO2-inspired) |
Usage
Secrets Manager
Create, load, and save encrypted key-value stores with AES-256-CBC encryption and HMAC authentication.
// Create a new store
var secrets = SecretsManager.CreateStore();
// Generate or load an encryption key
secrets.GenerateKey();
secrets.ExportKey("secrets.key"); // Save key for later
// Or load a key from file / environment variable / password
secrets.LoadKeyFromFile("secrets.key");
secrets.LoadKeyFromEnvironmentVariable("MY_SECRETS_KEY");
secrets.LoadKeyFromPassword("my-master-password");
// Store and retrieve secrets
secrets.Set("DatabasePassword", "super-secret-value");
secrets.Set("ApiKey", "sk-abc123xyz");
string dbPassword = secrets.Get("DatabasePassword");
// Try-get pattern
if (secrets.TryGetValue<string>("ApiKey", out var apiKey))
{
Console.WriteLine($"API Key loaded: {apiKey.Substring(0, 4)}...");
}
// Delete a secret
secrets.Delete("OldSecret");
// List all keys
foreach (var key in secrets.Keys)
{
Console.WriteLine(key);
}
// Save the encrypted store to file
secrets.SaveStore("secrets.json");
// Load an existing store
var loaded = SecretsManager.LoadStore("secrets.json");
loaded.LoadKeyFromFile("secrets.key");
string value = loaded.Get("DatabasePassword");
AntiDebugger
// Start monitoring for debugging attempts at application startup
AntiDebuggerModule.Start();
// Stop the module
AntiDebuggerModule.Stop();
// Manually trigger a crash to confuse reverse engineers
AntiDebuggerModule.Crash();
Detects:
- Debugging tools (dnSpy, x64dbg, windbg, ollydbg)
- Network monitors (Fiddler, Wireshark, Proxifier)
- Disassemblers/decompilers (IDA64, ILSpy, dotPeek)
AntiDump
Corrupts PE headers and section tables at runtime to prevent memory dumpers from producing a valid executable copy.
// Call at application startup
AntiDumpModule.Start();
// Stop the module
AntiDumpModule.Stop();
Bytes Generator
// Generate cryptographically secure random bytes
byte[] randomBytes = BytesGenerator.RandomBytes(16);
// Derive bytes from a password using PBKDF2
string password = "securepassword";
byte[] salt = BytesGenerator.RandomBytes(8);
byte[] derivedBytes = BytesGenerator.BytesFromPassword(password, salt, 16);
// Convert bytes to/from hex string
string hexString = BytesGenerator.BytesToString(randomBytes);
byte[] bytesFromHex = BytesGenerator.StringToBytes(hexString);
Data Compressor
byte[] data = Encoding.UTF8.GetBytes("This is some data to compress");
byte[] compressed = DataCompressor.Compress(data);
byte[] decompressed = DataCompressor.Decompress(compressed);
string original = Encoding.UTF8.GetString(decompressed);
Data Encryptor
// Encrypt any serializable object
string originalData = "Sensitive data";
byte[] key = BytesGenerator.RandomBytes(32); // AES-256
byte[] iv = BytesGenerator.RandomBytes(16);
byte[] encrypted = DataEncryptor.Encrypt(originalData, key, iv);
// Decrypt back to the original type
string decrypted = DataEncryptor.Decrypt<string>(encrypted, key, iv);
File Encryptor
byte[] key = BytesGenerator.RandomBytes(32); // AES-256
byte[] iv = BytesGenerator.RandomBytes(16);
// Encrypt a file
FileEncryptor.Encrypt("document.pdf", "document.pdf.enc", key, iv);
// Decrypt it back
FileEncryptor.Decrypt("document.pdf.enc", "document_decrypted.pdf", key, iv);
Hash Computer
byte[] data = Encoding.UTF8.GetBytes("This is my data");
// Compute a cryptographic hash
byte[] hash = HashComputer.Compute(data);
// Verify data integrity
bool isMatch = HashComputer.Verify(data, hash);
Password Validator
Validates password strength against configurable rules including minimum length, complexity requirements, and common password rejection.
var result = PasswordValidator.Validate("MyP@ssw0rd!2024",
minLength: 12,
requireUppercase: true,
requireLowercase: true,
requireDigit: true,
requireSpecialChar: true);
if (!result.IsValid)
{
Console.WriteLine(result.Message);
}
Input Sanitizer
Prevents injection attacks by sanitizing strings for safe use in file paths, commands, and data storage.
// Sanitize a key name (only allows alphanumeric, hyphens, underscores, dots)
string safeKey = InputSanitizer.SanitizeKeyName("my../key<>name"); // "my..keyname" -> only safe chars
// Prevent path traversal attacks (removes ".." and "~")
string safePath = InputSanitizer.SanitizePath("../../etc/passwd");
Rate Limiter
Prevents brute-force attacks by tracking failed attempts per identifier with configurable lockout periods.
var limiter = new RateLimiter(
maxAttempts: 5,
lockoutDuration: TimeSpan.FromMinutes(15),
attemptWindow: TimeSpan.FromMinutes(5));
// Check if locked out before allowing login
if (limiter.IsLockedOut("user@example.com"))
{
Console.WriteLine("Account is locked. Try again later.");
return;
}
// On failed login
limiter.RecordFailedAttempt("user@example.com");
// On successful login - reset the counter
limiter.Reset("user@example.com");
Secure Key Derivation
Derives encryption keys from passwords using PBKDF2-HMAC-SHA512 with OWASP-recommended 600,000 iterations.
// Derive a key with an existing salt
byte[] salt = BytesGenerator.RandomBytes(32);
byte[] key = SecureKeyDerivation.DeriveKey("mypassword", salt);
// Derive a key and generate a random salt (store the salt for re-derivation)
var (derivedKey, generatedSalt) = SecureKeyDerivation.DeriveKeyWithSalt("mypassword");
Secret Masker
Redacts sensitive data from strings to prevent accidental exposure in logs or error messages.
// Mask a secret entirely
string masked = SecretMasker.Mask("my-api-key-12345"); // "***REDACTED***"
// Show a prefix for identification
string partial = SecretMasker.Mask("my-api-key-12345", visiblePrefixLength: 4); // "my-a***REDACTED***"
// Redact passwords from connection strings
string safeLog = SecretMasker.RedactConnectionString("Server=db;Password=secret123;");
// Result: "Server=db;Password=***REDACTED***;"
// Redact all sensitive patterns (passwords, bearer tokens, API keys)
string sanitized = SecretMasker.RedactSensitivePatterns("Authorization: Bearer eyJhbGciOi...");
// Result: "Authorization: Bearer ***REDACTED***"
// Redact known secret values from any string
string output = SecretMasker.RedactValues("Connected with key abc123", "abc123");
// Result: "Connected with key ***REDACTED***"
Secure Configuration Provider
Stores secrets encrypted at rest so they are never in plain text in configuration files or source control.
// Create from an environment variable (recommended for production)
using var config = SecureConfigurationProvider.FromEnvironmentVariable("MY_APP_ENCRYPTION_KEY");
// Or provide a key directly (load from vault/HSM, never hardcode!)
byte[] key = BytesGenerator.RandomBytes(32);
using var config = new SecureConfigurationProvider(key);
// Encrypt a value for storage in config files
string encrypted = config.EncryptValue("ConnectionString", "Server=db;Password=secret");
// Result: "ENC:base64encodeddata..."
// Decrypt at runtime
string connectionString = config.DecryptValue("ConnectionString", encrypted);
// Check if a value is already encrypted
bool isEncrypted = encrypted.StartsWith("ENC:");
Sensitive Data Guard
Scans strings for potential plain-text secrets like AWS keys, GitHub tokens, JWTs, connection strings, and more.
string configContent = File.ReadAllText("appsettings.json");
var findings = SensitiveDataGuard.Scan(configContent);
foreach (var finding in findings)
{
Console.WriteLine($"⚠️ Detected {finding.PatternName} at position {finding.Position} (length: {finding.Length})");
}
Detects:
- AWS Access Keys and Secret Keys
- GitHub tokens (ghp_, gho_, ghu_, ghs_, ghr_)
- Generic API keys and secrets
- Connection string passwords
- Private keys (RSA, EC, DSA)
- Bearer and JWT tokens
- Azure Storage keys
- Slack tokens
Audit Logger
Tamper-evident logging using HMAC chains. Each log entry is cryptographically linked to the previous one, making any tampering detectable.
byte[] hmacKey = BytesGenerator.RandomBytes(32);
var logger = new AuditLogger("audit.log", hmacKey);
// Log security-relevant actions
logger.Log("admin", "Created user 'jane'");
logger.Log("jane", "Changed password");
logger.Log("admin", "Deleted user 'john'");
// Each line in the log file contains: timestamp|user|action|hmac
// The HMAC chain ensures no entry can be modified or removed without detection
Safe Vault
Encrypted item storage with AES-GCM encryption and HMAC integrity verification. Items are persisted to disk automatically.
byte[] masterKey = BytesGenerator.RandomBytes(32);
var vault = new SafeVault(masterKey, "vault.dat");
// Or create from an environment variable
var vault = SafeVault.FromEnvironmentVariable("VAULT_KEY", "vault.dat");
// Store items (passwords, certificates, keys, documents)
vault.StoreItem("db-password", ItemType.Password, Encoding.UTF8.GetBytes("super-secret"));
vault.StoreItem("tls-cert", ItemType.Certificate, File.ReadAllBytes("cert.pfx"));
// Retrieve items
byte[] password = vault.RetrieveItem("db-password");
string dbPass = Encoding.UTF8.GetString(password);
// List all stored items
string[] itemNames = vault.ListItems();
SecureItem[] allItems = vault.GetAllItems();
Secure Credential Store
Encrypt and decrypt credentials using AES-GCM. Never store passwords or connection strings in plain text.
// Create from environment variable (recommended)
var store = SecureCredentialStore.FromEnvironmentVariable("CREDENTIAL_STORE_KEY");
// Or provide a key directly
byte[] masterKey = BytesGenerator.RandomBytes(32);
using var store = new SecureCredentialStore(masterKey);
// Protect a credential for safe storage
string encrypted = store.Protect("Server=prod;Password=MyP@ss!");
// Store 'encrypted' in config files, databases, etc.
// Unprotect when needed at runtime
string original = store.Unprotect(encrypted);
Environment Variable Manager
Securely manage environment variables with optional AES-GCM encryption so secrets are never stored in plain text.
// Plain text operations
EnvironmentVariableManager.Set("APP_MODE", "production");
string mode = EnvironmentVariableManager.Get("APP_MODE");
bool exists = EnvironmentVariableManager.Exists("APP_MODE");
EnvironmentVariableManager.Delete("APP_MODE");
// Encrypted operations (secrets never stored in plain text)
byte[] protectionKey = BytesGenerator.RandomBytes(32);
EnvironmentVariableManager.SetEncrypted("DB_PASSWORD", "super-secret", protectionKey);
string decrypted = EnvironmentVariableManager.GetEncrypted("DB_PASSWORD", protectionKey);
TOTP Manager
Generate time-based one-time passwords (RFC 6238) for two-factor authentication.
// Generate a secret key for the user
byte[] secretKey = BytesGenerator.RandomBytes(20);
// Generate a TOTP code (6 digits, 30-second interval)
string code = TotpManager.GenerateTotp(secretKey);
Console.WriteLine($"Your code: {code}");
// Generate an otpauth:// URI for QR code scanning (Google Authenticator, Authy, etc.)
string uri = TotpManager.GenerateOtpUri("user@example.com", "MyApp", secretKey);
// Result: "otpauth://totp/MyApp:user%40example.com?secret=BASE32KEY&issuer=MyApp&digits=6&period=30"
User Manager
User account management with secure PBKDF2 password hashing, role-based access, and integrated rate limiting.
// Create with optional rate limiter
var rateLimiter = new RateLimiter(maxAttempts: 5);
var userManager = new UserManager("users.json", rateLimiter);
// Create users with role assignment
userManager.CreateUser("admin", "Str0ng!P@ssw0rd123", UserRole.Admin);
userManager.CreateUser("jane", "An0ther$ecure!Pass", UserRole.Standard);
// Authenticate (respects rate limiting)
bool authenticated = userManager.Authenticate("jane", "An0ther$ecure!Pass");
Secure Client / Server
TLS-secured client/server communication with optional mutual certificate authentication and auth tokens.
// --- Server setup ---
var serverCert = new X509Certificate2("server.pfx", "certpassword");
byte[] vaultKey = BytesGenerator.RandomBytes(32);
var vault = new SafeVault(vaultKey, "server-vault.dat");
var server = new SecureServer(
port: 5000,
cert: serverCert,
vault: vault,
requireClientCertificate: true,
authToken: "my-secret-token");
await server.StartAsync(cancellationToken);
// --- Client setup ---
var client = new SecureClient(
host: "localhost",
port: 5000,
validateServerCertificate: true,
clientCertificate: new X509Certificate2("client.pfx", "certpassword"));
string response = await client.SendCommandAsync("STORE:key:value");
File Sharing Manager
Encrypt files for specific recipients using per-user keys. Only the intended recipient can decrypt.
var sharing = new FileSharingManager();
// Encrypt a file for a specific user
byte[] userKey = BytesGenerator.RandomBytes(32); // recipient's key
byte[] fileData = File.ReadAllBytes("document.pdf");
byte[] encryptedForUser = sharing.EncryptForUser(fileData, userKey);
// Share the encrypted file (e.g., store on server)
sharing.ShareFile("doc-001", encryptedForUser);
// Recipient retrieves and decrypts
byte[] retrieved = sharing.RetrieveShared("doc-001");
byte[] decrypted = sharing.DecryptForUser(retrieved, userKey);
File.WriteAllBytes("document_received.pdf", decrypted);
Passwordless Authenticator
Cross-platform passwordless authentication using ECDSA (P-256) challenge-response. Inspired by FIDO2/WebAuthn concepts, works on all platforms (Windows, Linux, macOS) without platform-specific dependencies.
var auth = new PasswordlessAuthenticator("credentials.json");
// --- Registration ---
// Server generates key pair; client stores private key securely
var credential = auth.Register("alice", "My Laptop", out byte[] privateKey);
// Store privateKey securely on the client device
// Or: client generates its own key pair
PasswordlessAuthenticator.GenerateKeyPair(out byte[] publicKey, out byte[] clientPrivateKey);
var credential2 = auth.RegisterPublicKey("alice", publicKey, "My Phone");
// --- Authentication ---
// 1. Server creates a challenge
var challenge = auth.CreateChallenge("alice");
// 2. Client signs the challenge with their private key
var signature = PasswordlessAuthenticator.SignChallenge(privateKey, challenge.ChallengeBytes);
// 3. Server verifies the signature
bool success = auth.VerifyChallenge(
challenge.ChallengeId,
credential.CredentialId,
signature,
signatureCounter: 1);
// --- Credential Management ---
// List all credentials for a user
var credentials = auth.GetCredentials("alice");
// Remove a credential
auth.RemoveCredential("alice", credential.CredentialId);
Features:
- ECDSA P-256 signatures
- Time-limited challenges with configurable expiry
- Signature counter for cloned authenticator detection
- Integrated rate limiting
- Multiple credentials per user (multi-device support)
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 is compatible. net5.0-windows was computed. net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 is compatible. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.1 is compatible. |
| .NET Framework | net481 is compatible. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETFramework 4.8.1
- EonaCat.Json (>= 2.2.2)
- EonaCat.Versioning.Helpers (>= 1.0.2)
- Microsoft.CSharp (>= 4.7.0)
- System.Buffers (>= 4.6.1)
- System.Memory (>= 4.6.3)
-
.NETStandard 2.1
- EonaCat.Json (>= 2.2.2)
- EonaCat.Versioning.Helpers (>= 1.0.2)
- Microsoft.CSharp (>= 4.7.0)
- System.Buffers (>= 4.6.1)
- System.Memory (>= 4.6.3)
-
net5.0
- EonaCat.Json (>= 2.2.2)
- EonaCat.Versioning.Helpers (>= 1.0.2)
- Microsoft.CSharp (>= 4.7.0)
- System.Buffers (>= 4.6.1)
- System.Memory (>= 4.6.3)
-
net6.0
- EonaCat.Json (>= 2.2.2)
- EonaCat.Versioning.Helpers (>= 1.0.2)
- Microsoft.CSharp (>= 4.7.0)
- System.Buffers (>= 4.6.1)
- System.Memory (>= 4.6.3)
-
net7.0
- EonaCat.Json (>= 2.2.2)
- EonaCat.Versioning.Helpers (>= 1.0.2)
- Microsoft.CSharp (>= 4.7.0)
- System.Buffers (>= 4.6.1)
- System.Memory (>= 4.6.3)
-
net8.0
- EonaCat.Json (>= 2.2.2)
- EonaCat.Versioning.Helpers (>= 1.0.2)
- Microsoft.CSharp (>= 4.7.0)
- System.Buffers (>= 4.6.1)
- System.Memory (>= 4.6.3)
-
net9.0
- EonaCat.Json (>= 2.2.2)
- EonaCat.Versioning.Helpers (>= 1.0.2)
- Microsoft.CSharp (>= 4.7.0)
- System.Buffers (>= 4.6.1)
- System.Memory (>= 4.6.3)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.