Davasorus.Utility.DotNet.Encryption 2026.2.1.3

dotnet add package Davasorus.Utility.DotNet.Encryption --version 2026.2.1.3
                    
NuGet\Install-Package Davasorus.Utility.DotNet.Encryption -Version 2026.2.1.3
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Davasorus.Utility.DotNet.Encryption" Version="2026.2.1.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Davasorus.Utility.DotNet.Encryption" Version="2026.2.1.3" />
                    
Directory.Packages.props
<PackageReference Include="Davasorus.Utility.DotNet.Encryption" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Davasorus.Utility.DotNet.Encryption --version 2026.2.1.3
                    
#r "nuget: Davasorus.Utility.DotNet.Encryption, 2026.2.1.3"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Davasorus.Utility.DotNet.Encryption@2026.2.1.3
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Davasorus.Utility.DotNet.Encryption&version=2026.2.1.3
                    
Install as a Cake Addin
#tool nuget:?package=Davasorus.Utility.DotNet.Encryption&version=2026.2.1.3
                    
Install as a Cake Tool

Davasorus.Utility.DotNet.Encryption

Overview

Davasorus.Utility.DotNet.Encryption provides robust encryption and decryption utilities for .NET applications. It is designed to help developers securely handle sensitive data using modern cryptographic standards, with a focus on ease of use, maintainability, and extensibility.

Features

  • Symmetric encryption and decryption (AES)
  • Support for multiple usage scenarios (API, Web, Desktop, Static, Dynamic)
  • Strong key derivation using PBKDF2 (Rfc2898DeriveBytes)
  • Consistent error handling and logging
  • Asynchronous and synchronous APIs (V2 and V1, respectively)
  • .NET 8 compatibility
  • OpenTelemetry distributed tracing integration for comprehensive observability

OpenTelemetry Integration

This package includes comprehensive OpenTelemetry instrumentation for distributed tracing and observability across all encryption and decryption operations.

Telemetry Data Emitted

Activities (Spans):

  • Encryption.EncryptValue - Service-level encryption operations (V2)
  • Encryption.Encrypt - Client-level encryption operations (V2)
  • Encryption.V1.Encrypt - Legacy encryption operations (V1)
  • Decryption.DecryptValue - Service-level decryption operations (V2)
  • Decryption.Decrypt - Client-level decryption operations (V2)
  • Decryption.V1.Decrypt - Legacy decryption operations (V1)

Tags (Attributes):

  • encryption.usage / decryption.usage - Usage type (Static, Dynamic, api, web, desktop)
  • encryption.operation / decryption.operation - Operation type (encrypt/decrypt)
  • encryption.input_length / decryption.input_length - Input data length in characters
  • encryption.output_length / decryption.output_length - Output data length in characters
  • encryption.valid_usage / decryption.valid_usage - Whether the usage type is valid
  • encryption.success / decryption.success - Whether the operation succeeded
  • encryption.version / decryption.version - API version (v1 for legacy APIs)
  • crypto.algorithm - Encryption algorithm used (AES)
  • crypto.key_derivation - Key derivation function (PBKDF2-HMAC-SHA512 for V2, PBKDF2-HMAC-SHA1 for V1)
  • crypto.iterations - PBKDF2 iteration count (10,000)

Events:

  • encoding.completed - Unicode encoding phase completed (encryption) with bytes_length
  • decoding.completed - Base64 decoding phase completed (decryption) with bytes_length
  • crypto.started - Cryptographic operation started
  • crypto.completed - Cryptographic operation completed
  • exception - Exception occurred with full exception details (type, message, stacktrace)

Configuring Telemetry

The package uses Tyler.Utility.Encryption as the ActivitySource name. To enable telemetry collection, configure OpenTelemetry in your application startup:

using OpenTelemetry.Trace;

// In Program.cs or Startup.cs
builder.Services.AddOpenTelemetry()
    .WithTracing(tracing => tracing
        .AddSource("Tyler.Utility.Encryption") // Enable encryption telemetry
        .AddAspNetCoreInstrumentation()        // Optional: ASP.NET Core tracing
        .AddHttpClientInstrumentation()        // Optional: HTTP client tracing
        .AddConsoleExporter()                  // For development
        // OR for production:
        .AddOtlpExporter(options =>
        {
            options.Endpoint = new Uri("http://your-otel-collector:4317");
        })
    );

Trace Context Integration

All encryption and decryption operations automatically include trace context (TraceId, SpanId, ParentSpanId) in structured log messages. This enables seamless correlation between:

  • Distributed traces across microservices
  • Application logs
  • Performance metrics
  • Error tracking

Example log output with trace context:

{
  "timestamp": "2025-01-15T10:30:45.123Z",
  "level": "Information",
  "message": "Encryption complete",
  "TraceId": "4bf92f3577b34da6a3ce929d0e0e4736",
  "SpanId": "00f067aa0ba902b7",
  "ParentSpanId": "b7ad6b7169203331",
  "Usage": "Static",
  "InputLength": 256
}

Performance Analysis

The granular events enable detailed performance analysis:

  1. Encoding Phase - Time spent converting data to bytes

    • Encryption: Unicode encoding (encoding.completed event)
    • Decryption: Base64 decoding (decoding.completed event)
  2. Cryptographic Phase - Time spent in AES operations

    • Between crypto.started and crypto.completed events
    • Includes key derivation (PBKDF2) and encryption/decryption

Use these events in your APM tool to identify bottlenecks and optimize performance.

Security Considerations

No sensitive data is exposed in telemetry:

  • ✅ Only metadata is logged (lengths, usage types, algorithms)
  • ❌ Plaintext values are never included in traces
  • ❌ Encrypted values are never included in traces
  • ❌ Encryption keys are never included in traces
  • ❌ Salts are never included in traces

Exception messages are captured for debugging, but they do not contain sensitive cryptographic material.

Example: Full Trace

Span: Encryption.EncryptValue [Service]
├─ Tags: encryption.usage=Static, encryption.operation=encrypt,
│        encryption.input_length=256, crypto.algorithm=AES,
│        crypto.key_derivation=PBKDF2-HMAC-SHA512, crypto.iterations=10000
├─ Child Span: Encryption.Encrypt [Client]
│  ├─ Event: encoding.completed (bytes_length=512)
│  ├─ Event: crypto.started
│  ├─ Event: crypto.completed
│  └─ Tags: encryption.output_length=344, encryption.success=true
└─ Status: Ok

Getting Started

  1. Reference the library in your .NET project.
  2. Register the services and clients with your DI container (see below).
  3. Only interact with the service interfaces (IEncryptionService, IDecryptionService) in your application code. The service manages all communication with the client internally.

Note: Do not use the client classes directly in your application code. The service layer encapsulates all client logic, error handling, and logging.

Usage Example

V1 (Synchronous, legacy):

var encrypt = new Encrypt(logger);
var encrypted = encrypt.EncryptValue(model);
var decrypt = new Decrypt(logger);
var decrypted = decrypt.DecryptValue(model);

V2 (Asynchronous, recommended):

// Register services and clients in DI (see below) 

// In your consuming code, inject IEncryptionService and IDecryptionService
public class MyClass
{
    private readonly IEncryptionService _encryptionService;
    private readonly IDecryptionService _decryptionService;

    public MyClass(IEncryptionService encryptionService, IDecryptionService decryptionService)
    {
        _encryptionService = encryptionService;
        _decryptionService = decryptionService;
    }

    public async Task<string> EncryptAndDecrypt(UtilitySettingsModel model)
    {
        var encrypted = await _encryptionService.EncryptValue(model);
        var decrypted = await _decryptionService.DecryptValue(model);
        return decrypted;
    }
}

API Overview

  • V1
    • EncryptValue(UtilitySettingsModel model): string
      Synchronously encrypts the provided UtilitySettingsModel and returns the encrypted string. This method is part of the legacy V1 API and is intended for use in synchronous workflows.

    • DecryptValue(UtilitySettingsModel model): string
      Synchronously decrypts the provided UtilitySettingsModel and returns the decrypted string. Use this method when asynchronous processing is not required.

    • Usage enum:

      • api
        For API-based scenarios where encryption/decryption is performed in service endpoints.
      • web
        For web application scenarios, such as encrypting data in web forms or cookies.
      • desktop
        For desktop application scenarios, such as encrypting configuration files or user data.
  • V2
    • EncryptValueAsync(UtilitySettingsModel model): Task<string>
      Asynchronously encrypts the provided UtilitySettingsModel. This method is internal to the service and not intended for direct use.

    • DecryptValueAsync(UtilitySettingsModel model): Task<string>
      Asynchronously decrypts the provided UtilitySettingsModel. This method is internal to the service and not intended for direct use.

    • Service API:

      • EncryptValue(UtilitySettingsModel model): Task<string>
        Public asynchronous method to encrypt a UtilitySettingsModel via the service interface.
      • DecryptValue(UtilitySettingsModel model): Task<string>
        Public asynchronous method to decrypt a UtilitySettingsModel via the service interface.
    • Usage enum:

      • Static
        For scenarios where encryption parameters remain constant.
      • Dynamic
        For scenarios where encryption parameters may change per operation.

Service/Client Pattern

  • Do not use IEncryptionClient or IDecryptionClient directly.
  • Always use IEncryptionService and IDecryptionService in your application code.
  • The service handles all error handling, logging, and client interaction.

Key Differences: V1 vs V2

Feature/Behavior V1 (Legacy) V2 (Current)
API Design Synchronous methods Asynchronous (Task-based, service-oriented)
Usage Enum api, web, desktop Static, Dynamic
Key Derivation PBKDF2, static salt, SHA1 PBKDF2, named salt ("Ivan Medvedev"), SHA512
Error Handling Returns empty string on error Returns empty string, logs error, throws for invalid usage
Logging ILogger<T> ILogger<T>
.NET Support .NET 8 .NET 8
Extensibility Limited Improved, interface-based, testable
Test Coverage Unit tests for all usage types Unit tests for all usage types, async tests

Summary of Improvements in V2

  • Fully async/await support for better scalability
  • Stronger key derivation (SHA512, named salt)
  • Usage enum is more generic (Static/Dynamic)
  • Improved error handling and logging
  • Interface-based design for easier testing and extension
  • Consistent base64 encoding/decoding (replaces '/' with '_' for URLs)
  • Strict service/client separation for DI

Dependency Injection (DI) Usage

V2 is designed for modern .NET dependency injection. Use the built-in extension methods from Tyler.Utility.DotNet.Encryption.Configuration:

Recommended: Extension methods (registers both encryption and decryption)

using Tyler.Utility.DotNet.Encryption.Configuration;

// Default (Scoped lifetime)
services.AddEncryptionServices();

// With custom lifetime
services.AddEncryptionServices(config => config.UseTransientLifetime());
services.AddEncryptionServices(config => config.UseSingletonLifetime());

Register only encryption or decryption:

services.AddEncryptionOnly();
services.AddDecryptionOnly();

Manual registration (alternative):

services.AddScoped<IEncryptionService, EncryptionService>();
services.AddScoped<IEncryptionClient, EncryptionClient>();
services.AddScoped<IDecryptionService, DecryptionService>();
services.AddScoped<IDecryptionClient, DecryptionClient>();

Note: Only inject and use IEncryptionService and IDecryptionService in your application code. The service manages all client interactions.

Example Test Cases

  • Encrypt and decrypt with all supported usage types
  • Handles invalid usage gracefully (returns empty string)
  • Logs errors on exceptions
  • Async tests for V2

Dependencies

License

MIT License

Contributing

Contributions are welcome! Please submit issues or pull requests for improvements.

Product Compatible and additional computed target framework versions.
.NET 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 was computed.  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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (4)

Showing the top 4 NuGet packages that depend on Davasorus.Utility.DotNet.Encryption:

Package Downloads
Davasorus.Utility.DotNet.SQS

Amazon SQS interaction for TEPS Utilities

Davasorus.Utility.DotNet.Auth

Handles Authentication for TEPS Utilities

Davasorus.Utility.DotNet.Api

API Interaction for TEPS Utilities with generic deserialization, configurable error reporting, and improved DI configuration. Supports REST, GraphQL, gRPC, WebSocket, SignalR, and SSE protocols.

SA.OpenSearchTool.Business

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2026.2.1.3 183 4/9/2026
2026.2.1.2 54 4/9/2026
2026.2.1.1 1,321 4/1/2026
2026.1.3.5 737 3/29/2026
2026.1.3.4 630 3/24/2026
2026.1.3.3 2,020 3/12/2026
2026.1.3.2 130 3/12/2026
2026.1.3.1 623 3/10/2026
2026.1.2.6 1,740 2/17/2026
2026.1.2.4 806 2/12/2026
2026.1.2.3 277 2/9/2026
2026.1.2.2 110 2/9/2026
2026.1.2.1 662 2/7/2026
2026.1.1.4 670 1/30/2026
2026.1.1.3 1,305 1/15/2026
2026.1.1.2 108 1/14/2026
2026.1.1.1 121 1/14/2026
2025.4.3.7 1,917 12/24/2025
2025.4.3.6 1,417 12/16/2025
2025.4.3.5 602 12/15/2025
Loading failed