Kapela.Security.Encryption 10.0.3

Prefix Reserved
dotnet add package Kapela.Security.Encryption --version 10.0.3
                    
NuGet\Install-Package Kapela.Security.Encryption -Version 10.0.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="Kapela.Security.Encryption" Version="10.0.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Kapela.Security.Encryption" Version="10.0.3" />
                    
Directory.Packages.props
<PackageReference Include="Kapela.Security.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 Kapela.Security.Encryption --version 10.0.3
                    
#r "nuget: Kapela.Security.Encryption, 10.0.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 Kapela.Security.Encryption@10.0.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=Kapela.Security.Encryption&version=10.0.3
                    
Install as a Cake Addin
#tool nuget:?package=Kapela.Security.Encryption&version=10.0.3
                    
Install as a Cake Tool

🔐 Kapela.Security.Encryption

Protégez les données sensibles de votre application .NET — mots de passe, chaînes de connexion, clés d'API — en les chiffrant directement dans votre configuration.


📦 Installation

dotnet add package Kapela.Security.Encryption

🗝️ Clé de chiffrement

Deux moyens de fournir la clé de chiffrement de votre application :

1. Au démarrage via SetEncryptionKey :

// Program.cs — à appeler avant AddKapelaEncryption
EncryptionHelper.SetEncryptionKey("MaCléPersonnalisée");

builder.Services.AddKapelaEncryption(builder.Configuration.Get<AppSettings>() ?? new());

2. Via la variable d'environnement KAPELA_ENCRYPTION_KEY, lue automatiquement au démarrage si SetEncryptionKey n'est pas appelé. Recommandé en production lorsque la clé est gérée par un secret manager ou une variable de pipeline :

export KAPELA_ENCRYPTION_KEY="MaCléPersonnalisée"

⚠️ La même clé doit être utilisée pour chiffrer et déchiffrer une valeur. Conservez-la précieusement (variable d'environnement, secret manager).


✏️ Chiffrement et déchiffrement

Opérations de base sur une valeur :

using Kapela.Security.Encryption;

string encrypted = EncryptionHelper.Encrypt("MonMotDePasse");
string plain     = EncryptionHelper.Decrypt(encrypted);

Versions sans exception, pratiques dans les initialisations :

if (EncryptionHelper.TryEncrypt("MonMotDePasse", out string encrypted)) { }
if (EncryptionHelper.TryDecrypt(encrypted, out string plain)) { }

🏷️ Déchiffrement automatique avec [Encrypted]

Décorez les propriétés sensibles de votre objet de configuration. AddKapelaEncryption les déchiffre automatiquement et enregistre l'objet comme singleton — en une seule ligne.

1. Déclarer le modèle

public class AppSettings
{
    public string ApiUrl { get; set; } = string.Empty;

    [Encrypted]
    public string ApiKey { get; set; } = string.Empty;

    [Encrypted]
    public SmtpSettings Smtp { get; set; } = new();
}

public class SmtpSettings
{
    public string Host { get; set; } = string.Empty;
    public int Port { get; set; }
    public string Username { get; set; } = string.Empty;

    [Encrypted]
    public string Password { get; set; } = string.Empty;
}

2. Enregistrer via l'injection de dépendances

// Program.cs
EncryptionHelper.SetEncryptionKey("MaCléPersonnalisée");

builder.Services.AddKapelaEncryption(builder.Configuration.Get<AppSettings>() ?? new());
// ✅ Les propriétés ApiKey et Smtp.Password sont déchiffrées
//    et AppSettings est enregistré comme singleton
// ⚠️ Smtp doit être décoré avec [Encrypted] pour que la récursion s'applique

3. Consommer dans un service

public class MonService(AppSettings settings)
{
    // ✅ settings.ApiKey est déjà déchiffré
}

Comportement en cas d'échec de déchiffrement

Mode Comportement si le déchiffrement échoue
KeepValue (défaut) La valeur d'origine est conservée
ReplaceByEmpty La propriété est vidée ("")
[Encrypted(EncryptedAttributeModes.KeepValue)]
public string ApiKey { get; set; } = string.Empty;

[Encrypted(EncryptedAttributeModes.ReplaceByEmpty)]
public string Secret { get; set; } = string.Empty;

Profondeur de récursion

AddKapelaEncryption descend jusqu'à 5 niveaux d'imbrication par défaut. Ce seuil est configurable via ParseObject si vous gérez le déchiffrement manuellement :

EncryptionHelper.ParseObject(settings, maxLevel: 10);

💡 La récursion ne s'applique qu'aux propriétés explicitement décorées avec [Encrypted]. Un objet imbriqué non décoré est ignoré, même s'il contient lui-même des propriétés [Encrypted].


🔀 Contexte de chiffrement indépendant

CreateContext crée un EncryptionContext isolé, avec sa propre clé, sans affecter le contexte global. Utile quand une application gère plusieurs clés simultanément (ex. migration, multi-tenant).

using Kapela.Security.Encryption;

using var ctx = EncryptionHelper.CreateContext("AutreCléPersonnalisée");

string encrypted = ctx.Encrypt("MonSecret");
string plain     = ctx.Decrypt(encrypted);

// Toutes les méthodes du contexte principal sont disponibles
ctx.ParseObject(settings);
string cs = ctx.GetConnectionString(configuration, "Default");

EncryptionContext est IDisposable — utilisez-le dans un bloc using.


🔌 Chaînes de connexion

// appsettings.json → "ConnectionStrings": { "Default": "<valeur chiffrée>" }

string cs = EncryptionHelper.GetConnectionString(builder.Configuration, "Default");
// Retourne la valeur déchiffrée, ou la valeur brute si le déchiffrement échoue

📂 Sections de configuration

Déchiffre toutes les valeurs directes d'une section :

IConfiguration smtp = EncryptionHelper.GetSection(builder.Configuration, "Smtp");

🔄 Compatibilité avec les valeurs .NET Framework

Si vous migrez depuis Kapela.Security.Encryption.Net4, utilisez IsNet4 = true pour déchiffrer les anciennes valeurs côte à côte avec les nouvelles :

[Encrypted(IsNet4 = true)]
public string AncienMotDePasse { get; set; } = string.Empty;

Pour migrer définitivement ces valeurs, utilisez l'outil CLI 👇


🛠️ Générer des valeurs chiffrées

Installez l'outil CLI Kapela.Security.Encryption.Tools pour produire vos valeurs chiffrées à placer dans appsettings.json :

dotnet tool install --global Kapela.Security.Encryption.Tools

Kapela-Encryption encrypt -p NomDeMonApplication -v "MonMotDePasse"
 >>> SGVsbG8gV29ybGQ...
Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  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 (1)

Showing the top 1 NuGet packages that depend on Kapela.Security.Encryption:

Package Downloads
Kapela.Security.Encryption.EntityFrameworkCore

Extension Entity Framework Core de Kapela.Security.Encryption : chiffrez de manière transparente les propriétés sensibles de vos entités, sans modifier votre code applicatif.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
10.0.3 152 5/11/2026
10.0.2 191 4/7/2026
10.0.0 358 12/4/2025
8.3.0 276 12/4/2025
8.2.0 3,563 5/26/2025
8.1.2 1,263 4/28/2025
1.1.2 214 4/2/2025
1.1.1 3,032 8/29/2024
1.1.0 221 8/28/2024
1.0.3 209 8/22/2024
1.0.2 171 7/11/2024
1.0.1 180 7/3/2024
1.0.0 169 6/3/2024