KNM.CryptoHelper 1.6.1

KNM.CryptoHelper

Production-ready cryptographic library for .NET enterprise applications.
Provides AES‑256 encryption with HMAC integrity, JWT authentication, API key generation, TOTP MFA, OTP generation, device fingerprinting, RSA digital signing/verification, BIP39 mnemonic handling, and multiple hash functions (MD5, SHA‑1, SHA‑2, RIPEMD‑160, etc.).

Installation

dotnet add package KNM.CryptoHelper

Configuration

DI Registration (.NET 10)

builder.Services.AddKnmCryptoCollection(options =>
{
    options.Crypto.CryptoPassword = "YourSecurePassword123!";
    options.Crypto.Iterations = 100_000;
    options.Jwt.JwtSecretKey = "your-jwt-secret-min-32-chars";
    options.Jwt.Issuer = "yourapp.com";
    options.ApiKey.ApiKeySalt = "your-hmac-salt";
    options.Mfa.Digits = 6;
    options.Mfa.Period = 30;
    options.Otp.Length = 6;
    options.Otp.ValidityDurationMinutes = 5;
    options.DeviceFingerprint.Enabled = true;
    options.DeviceFingerprint.SimilarityThreshold = 0.90;
    options.DeviceFingerprint.CacheExpiryDays = 90;
    options.Bcrypt.WorkFactor = 12;
    options.Rsa.PrivateKeyPath = "/keys/private.pem";
    options.Rsa.PublicKeyPath = "/keys/public.pem";
});

Fluent Override

builder.Services.AddKnmCryptoCollection()
    .WithCrypto(opt =>
    {
        opt.CryptoPassword = "YourSecurePassword123!";
        opt.Iterations = 200_000;
    })
    .WithJwt(opt =>
    {
        opt.JwtSecretKey = "your-jwt-secret-min-32-chars";
        opt.Issuer = "yourapp.com";
        opt.Audience = "yourapp-clients";
        opt.ExpirationMinutes = 60;
    })
    .WithApiKey(opt =>
    {
        opt.ApiKeySalt = "your-hmac-salt";
    })
    .WithMfa(opt =>
    {
        opt.Digits = 6;
        opt.Period = 30;
        opt.Algorithm = TotpHashAlgorithm.Sha256;
    })
    .WithOtp(opt =>
    {
        opt.Length = 6;
        opt.ValidityDurationMinutes = 5;
    })
    .WithDeviceFingerprint(opt =>
    {
        opt.Enabled = true;
        opt.SimilarityThreshold = 0.90;
        opt.CacheExpiryDays = 90;
    })
    .WithBcrypt(opt =>
    {
        opt.WorkFactor = 12;
    })
    .WithRsa(opt =>
    {
        opt.PrivateKeyPath = "/keys/private.pem";
        opt.PublicKeyPath = "/keys/public.pem";
        opt.PaddingMode = RsaPaddingMode.Pkcs1;
    });

Usage

Inject ICryptoHelper in your services/controllers:

public class AuthService
{
    private readonly ICryptoHelper _crypto;

    public AuthService(ICryptoHelper crypto)
    {
        _crypto = crypto;
    }
}

Text Encryption

string encrypted = _crypto.EncryptText("Sensitive data");
string decrypted = _crypto.DecryptText(encrypted);

// Legacy format (backward compatibility)
string legacyEncrypted = _crypto.EncryptTextLegacy("Sensitive data");
string legacyDecrypted = _crypto.DecryptTextLegacy(legacyEncrypted);

// Decrypt any format (auto-detects current vs legacy)
string plaintext = _crypto.DecryptAny(encryptedData);

// Migrate from legacy to current format (decrypt legacy → re-encrypt current)
string migrated = _crypto.MigrateEncryptedText(legacyEncrypted);

// Or enable automatic legacy detection on DecryptText via DI:
// builder.Services.AddKnmCryptoCollection()
//     .WithCrypto(opt => opt.AutoMigrateLegacy = true);
// Now DecryptText("legacy-data") works transparently

API Keys

// Generate
Guid userSalt = Guid.NewGuid();
DateTime expiration = DateTime.UtcNow.AddDays(30);
string apiKey = _crypto.GenerateApiKey(userSalt, expiration);

// Verify
bool isValid = _crypto.VerifyApiKey(userSalt, expiration, apiKey);

JWT Tokens

// Generate
string token = _crypto.GenerateJwtToken(
    userId: "123",
    email: "user@domain.com",
    username: "john.doe"
);

// Generate with custom claims
var claims = new Dictionary<string, string>
{
    ["roles"] = "Admin,User",
    ["tenantId"] = "TEN-456"
};
string tokenWithClaims = _crypto.GenerateJwtToken("123", "user@domain.com", "john.doe", claims);

// Legacy overload (ssid parameter — maintained for backward compatibility)
string legacyToken = _crypto.GenerateJwtToken("123", "user@domain.com", "john.doe", ssid: "session-id");

// Validate
var (isValid, jwtToken, expirationDate) = _crypto.JwtTokenIsValid(token);
if (isValid == "Valid")
{
    // Access claims via jwtToken.Claims
}

MFA TOTP

// Setup (registration/profile)
string encryptedSecret = _crypto.GenerateMfaSecret();
// Save encryptedSecret to database

string qrCode = _crypto.GenerateMfaQrCode("user@domain.com", encryptedSecret);
// Display: <img src="@qrCode" />

MfaObject mfaInfo = _crypto.GenerateMfaCode("user@domain.com", encryptedSecret);
// Display mfaInfo.Uri (for URI-based apps),
// or mfaInfo.PlainSecret for manual entry,
// or mfaInfo.QrCodeSvg for SVG QR code visualization

// Verify (login)
bool isValid = _crypto.VerifyMfaCode(user.EncryptedMfaSecret, "123456");

OTP Generation & Verification

// Generate + send
OtpResult otp = _crypto.GenerateOtp();
await db.SaveOtpAsync(userId, otp.Code, otp.ExpiryDate);
await email.SendAsync(user.Email, otp.Code);

// Verify
bool valid = _crypto.VerifyOtp(storedCode, userCode, storedExpiry);

Device Fingerprinting

// Generate fingerprint
string fingerprint = _crypto.GenerateDeviceFingerprint(context);

// Get device info
DeviceInfo device = _crypto.GetDeviceInfo(context);
// device.Browser, device.OS, device.DeviceType, device.DeviceFingerprint

// Compare fingerprints
double similarity = _crypto.CalculateFingerprintSimilarity(fp1, fp2);
bool isSameDevice = similarity >= 0.90; // compare against your configured threshold

// Inject device context (middleware)
await _crypto.InjectDeviceContextAsync(context, userId);
// Sets context.Items["DeviceInfo"], context.Items["DeviceFingerprint"], context.Items["MFARequired"]

Bcrypt Password Hashing

string passwordHash = _crypto.BcryptHashPassword("plaintextPassword", workFactor);
bool isMatch = _crypto.BcryptVerifyPassword("plaintextPassword", passwordHash);
bool needsUpgrade = _crypto.BcryptNeedsRehash(passwordHash, targetWorkFactor);

// Optional: upgrade to a new work factor on login
bool isValid = _crypto.BcryptUpgradePasswordHash(
    plainPassword: "plaintextPassword",
    oldHash: passwordHash,
    targetWorkFactor: 12,
    out string newHash);

if (isValid && newHash != null)
{
    // Persist newHash to DB to reduce load on old lower-cost hashes
}

Hashing

// Compute any standard hash (MD5, SHA1, SHA256, SHA3, RIPEMD160, etc.)
string hash = _crypto.ComputeHash("text", HashAlgorithmType.Sha256);

// Verify against an existing hash
bool matches = _crypto.VerifyHash("text", "existing-hash", HashAlgorithmType.Sha256);

// SHA-256 binary overload (for files, reports, byte arrays)
byte[] reportContent = File.ReadAllBytes("report.pdf");
string sha256 = _crypto.ComputeSha256(reportContent);

// Supported algorithms include:
// - MD5, SHA1, SHA224, SHA256, SHA384, SHA512
// - SHA3 variants (SHA3-256, SHA3-512)
// - RIPEMD-160 for cryptocurrency-style digests

RSA Signing & Verification

// Sign data with RSA private key
byte[] data = File.ReadAllBytes("report.pdf");
byte[] signature = _crypto.SignRsa(data);

// Verify signature with RSA public key
bool isValid = _crypto.VerifyRsa(data, signature);

// Combine with SHA-256 for report integrity
string hash = _crypto.ComputeSha256(data);
byte[] hashBytes = Encoding.UTF8.GetBytes(hash);
byte[] hashSignature = _crypto.SignRsa(hashBytes);

RSA keys can be configured via PEM strings, file paths, or X.509 certificates:

// Inline PEM keys
.WithRsa(opt =>
{
    opt.PrivateKeyPem = "-----BEGIN RSA PRIVATE KEY-----\n...";
    opt.PublicKeyPem = "-----BEGIN PUBLIC KEY-----\n...";
})

// File paths
.WithRsa(opt =>
{
    opt.PrivateKeyPath = "/keys/private.pem";
    opt.PublicKeyPath = "/keys/public.pem";
})

// X.509 certificate (public key only)
.WithRsa(opt =>
{
    opt.PrivateKeyPath = "/keys/private.pem";
    opt.CertificatePath = "/certs/signing.cer";
})

// PSS padding (recommended for new implementations)
.WithRsa(opt =>
{
    opt.PaddingMode = RsaPaddingMode.Pss;
})

BIP39 Mnemonic & Seed

// Generate 12-word italian mnemonic
string mnemonic = _crypto.GenerateMnemonic(wordCount: KnmWordCount.Twelve,language: KnmLanguage.English);

// Convert mnemonic to 64-byte BIP39 seed (hex)
string seed = _crypto.MnemonicToSeed("mnemonic", password: "optional-passphrase", language: KnmLanguage.English);

// Validate before sensitive operations
bool isValid = _crypto.ValidateMnemonic(mnemonic, KnmLanguage.English);

Configuration Options

public class Options
{
    public CryptoOptions Crypto { get; set; }
    public JwtOptions Jwt { get; set; }
    public ApiKeyOptions ApiKey { get; set; }
    public MfaOptions Mfa { get; set; }
    public OtpOptions Otp { get; set; }
    public DeviceFingerprintOptions DeviceFingerprint { get; set; }
    public BcryptOptions Bcrypt { get; set; }
    public RsaOptions Rsa { get; set; }
}

CryptoOptions

  • CryptoPassword: AES encryption password
  • SaltSize: Salt bytes (default 16)
  • IvSize: IV bytes (default 16)
  • KeySize: Key bytes (default 32)
  • Iterations: PBKDF2 iterations (default 100,000)
  • AutoMigrateLegacy: When true, DecryptText auto-detects and decrypts legacy format (default false)

JwtOptions

  • JwtSecretKey: HMAC‑SHA256 secret (min 32 chars)
  • Issuer: Token issuer
  • Audience: Token audience
  • ExpirationMinutes: Token lifetime (default 60)

MfaOptions

  • Digits: TOTP code length (default 6)
  • Period: Time step seconds (default 30)
  • Algorithm: Hash mode (SHA1/SHA256/SHA512)
  • VerificationWindow: Time tolerance (default ±1 step)
  • Issuer: QR code issuer name (default "KNM.CryptoHelper")

OtpOptions

  • Length: OTP digits (1–10, default 6)
  • ValidityDurationMinutes: Expiration time (default 5)

DeviceFingerprintOptions

  • Enabled: Enable device tracking (default true)
  • SimilarityThreshold: Match threshold 0.0–1.0 (default 0.90)
  • CacheExpiryDays: Trusted device cache duration (default 90)
  • MaskLevel: 32, 24, 20, 16 (default Subnet24 / 24)

BcryptOptions

  • WorkFactor: Bcrypt cost factor (default 12)

RsaOptions

  • PrivateKeyPem: Inline PEM private key string
  • PublicKeyPem: Inline PEM public key string
  • PrivateKeyPath: File path to PEM private key
  • PublicKeyPath: File path to PEM public key
  • CertificatePath: File path to X.509 certificate (public key extraction)
  • PaddingMode: Pkcs1 (default) or Pss

Technical Details

Feature Algorithm Format
Encryption AES‑256‑CBC + HMAC‑SHA256 Base64
API Keys HMAC‑SHA256 Base64
JWT HMAC‑SHA256 RFC 7519
MFA TOTP RFC 6238 Base32 secret
Fingerprint SHA‑256 32‑char hex
Mnemonic & Seed BIP39 12–24 word phrase
RSA Signing RSA + SHA‑256 PKCS1 or PSS
Hashing MD5/SHA‑1/SHA‑2/SHA‑3/RIPEMD‑160 Hex string

License

Proprietary — KoNiMa Software & More

Showing the top 20 packages that depend on KNM.CryptoHelper.

Packages Downloads
KNM.Reporting.AI
AI conversational agent for KNM.Reporting with Ollama tool use, session management, and multi-DbContext support
0

Version Downloads Last updated
1.7.1 7 12/04/2026
1.7.0 2 09/04/2026
1.6.1 4 04/04/2026
1.6.0 5 26/03/2026
1.5.1 4 25/03/2026
1.5.0 0 25/03/2026
1.4.9 4 05/03/2026
1.4.8 0 05/03/2026
1.4.7 2 24/02/2026
1.4.6 1 24/02/2026
1.4.5 2 23/02/2026
1.3.9 4 09/01/2026
1.3.8 1 08/01/2026
1.3.7 1 08/01/2026
1.3.6 1 08/01/2026
1.3.5 1 08/01/2026