Pitasoft.Safety 7.1.1

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

Pitasoft.Safety

NuGet version NuGet downloads License: MIT .NET Support Build Status

English | Castellano


English

Pitasoft.Safety is a .NET library providing modern, secure, and easy-to-use cryptographic tools for application security. It includes password generation and validation, secure password hashing (PBKDF2), AEAD encryption (AES-GCM), and multiple hashing/HMAC algorithms.

Features

  • Password Generation & Validation: Securely generate and validate passwords based on customizable requirements.
  • Secure Password Hashing: PBKDF2 with SHA-256 and configurable iterations.
  • AEAD Encryption: Secure authenticated encryption with AES-GCM and PBKDF2 key derivation.
  • Hashing: Support for SHA-2, SHA-3, BLAKE2b, BLAKE2s, and BLAKE3. MD5 and SHA-1 remain available as obsolete options for compatibility.
  • HMAC / Keyed Hashing: Support for HMAC-SHA2 and keyed BLAKE2b.

Supported Frameworks

  • net8.0
  • net9.0
  • net10.0

Quick Practical Examples

Register a user password
using Pitasoft.Safety;

var plainPassword = "MyStr0ngP@ss!";
var storedHash = PasswordHasher.Create(plainPassword);

// Save storedHash in your database
Validate login credentials
using Pitasoft.Safety;

var inputPassword = "MyStr0ngP@ss!";
var storedHash = GetPasswordHashFromDatabase();

if (PasswordHasher.Verify(inputPassword, storedHash))
{
    Console.WriteLine("Login OK");
}
else
{
    Console.WriteLine("Invalid credentials");
}
Generate a password that matches your policy
using Pitasoft.Safety;

var policy = new PasswordOption
{
    RequiredLength = 16,
    RequiredUniqueChars = 6,
    RequireUppercase = true,
    RequireLowercase = true,
    RequireDigit = true,
    RequireNonAlphanumeric = true
};

var generatedPassword = Password.Generate(policy);
var isValid = Password.IsValid(generatedPassword, policy);
Encrypt and decrypt application data with a password
using Pitasoft.Safety;

var token = SecureCrypt.EncryptAead("ConnectionStringOrSecret", "master-password");
var original = SecureCrypt.DecryptAead(token, "master-password");
Hash a value for fingerprinting and sign a payload
using System.Text;
using Pitasoft.Safety;
using Pitasoft.Safety.Extensions;

var fingerprint = "document-content".Hash(AlgorithmType.Sha256, "tenant-a");
var macKey = Encoding.UTF8.GetBytes("shared-secret-key");
var signature = "payload-to-protect".Hmac(HmacAlgorithmType.HmacSha256, macKey);

API Reference & Examples

1. Password Management (Password & PasswordOption)

Provides methods to generate and validate passwords.

  • Password.Generate(PasswordOption? option = null): Generates a cryptographically secure random password.
  • Throws if the configured policy is impossible to satisfy, for example when required unique characters exceed the requested length.
  • Password.IsValid(string? password, PasswordOption? option = null): Validates if a password meets the requirements.
  • PasswordOption: Defines password rules. Defaults are length 6, unique chars 1, and all category flags enabled.

Example:

using Pitasoft.Safety;

var options = new PasswordOption 
{ 
    RequiredLength = 12, 
    RequiredUniqueChars = 4,
    RequireUppercase = true,
    RequireLowercase = true,
    RequireDigit = true,
    RequireNonAlphanumeric = true
};

string password = Password.Generate(options);
bool isValid = Password.IsValid(password, options);
2. Password Hashing (PasswordHasher)

Secure storage for passwords using PBKDF2.

Use this API for user passwords. The generic Hash(...) helpers are meant for fingerprints and non-password scenarios.

  • PasswordHasher.Create(string password, int iterations = 200000): Creates a secure hash token (pbkdf2-v1$iter$salt$hash).
  • PasswordHasher.Verify(string password, string token): Verifies a password against a hash token.
  • Returns false for invalid or malformed tokens.

Example:

string hash = PasswordHasher.Create("my-password");
bool verified = PasswordHasher.Verify("my-password", hash);
3. AEAD Encryption (SecureCrypt)

High-level API for AES-GCM encryption with password-based or direct key derivation.

  • SecureCrypt.EncryptAead(string plaintext, string password, int iterations = 200000): Encrypts text using a password-derived key (PBKDF2).
  • SecureCrypt.DecryptAead(string token, string password): Decrypts a versioned token using a password-derived key.
  • SecureCrypt.EncryptAeadWithKey(string plaintext, ReadOnlySpan<byte> key, ReadOnlySpan<byte> salt, int iterations): Encrypts text using a direct cryptographic key and includes salt/iterations in the token for future decryption.
  • SecureCrypt.DecryptAeadWithKey(string token, ReadOnlySpan<byte> key): Decrypts a versioned token using a direct cryptographic key.

Example (Password-based):

string token = SecureCrypt.EncryptAead("my secret message", "strong-password");
string decoded = SecureCrypt.DecryptAead(token, "strong-password");

Example (Direct Key):

byte[] key = System.Security.Cryptography.RandomNumberGenerator.GetBytes(32);
byte[] salt = System.Security.Cryptography.RandomNumberGenerator.GetBytes(16);
string token = SecureCrypt.EncryptAeadWithKey("confidential", key, salt, 200000);
string decoded = SecureCrypt.DecryptAeadWithKey(token, key);
4. Extensions (Pitasoft.Safety.Extensions)

Convenient extension methods for strings.

  • Extensions.ChangeKey(string key): Sets the global encryption key. Configure it once during application startup.
  • str.Encrypt() / str.Decrypt(): Encrypts/Decrypts using the global key.
  • str.EncryptKey(string key) / str.DecryptKey(string key): Encrypts/Decrypts using a specific key.
  • str.Hash(AlgorithmType type, string salt = ""): Generates a hash. Supported values are Md5 and Sha1 as obsolete options, plus Sha256, Sha384, Sha512, Sha3_256, Sha3_512, Blake2b_256, Blake2b_512, Blake2s_256, and Blake3. Intended for fingerprints, not password storage.
  • str.Hmac(HmacAlgorithmType type, byte[] key): Generates an HMAC or keyed hash. Supported values are HmacSha256, HmacSha384, HmacSha512, Blake2b_256, and Blake2b_512.

Compatibility note: when a salt is provided, the library now encodes the input and salt as separate fields before hashing. This avoids ambiguous concatenation collisions and changes the resulting hash compared to older versions for the same (input, salt) pair.

Note: the Blake2b_* values in HmacAlgorithmType are keyed BLAKE2b hashes, not standard HMAC constructions.

5. Public Enums
  • AlgorithmType: Selects the hash algorithm used by Hash(...).
  • HmacAlgorithmType: Selects the HMAC or keyed-hash algorithm used by Hmac(...).
  • TypeCharacter: Public enum representing password character categories.

Example:

using Pitasoft.Safety.Extensions;

// Hashing
string sha512 = "hello".Hash(AlgorithmType.Sha512);
string blake3 = "hello".Hash(AlgorithmType.Blake3);

// HMAC
byte[] key = System.Text.Encoding.UTF8.GetBytes("secret-key");
string hmac = "message".Hmac(HmacAlgorithmType.HmacSha256, key);

[Castellano]

Pitasoft.Safety es una librería para .NET que proporciona herramientas criptográficas modernas, seguras y fáciles de usar para la seguridad de aplicaciones. Incluye generación y validación de contraseñas, hash seguro de contraseñas (PBKDF2), cifrado AEAD (AES-GCM) y múltiples algoritmos de Hash/HMAC.

Características

  • Generación y Validación de Contraseñas: Genera y valida contraseñas de forma segura basándose en requisitos personalizables.
  • Hash de Contraseñas Seguro: PBKDF2 con SHA-256 e iteraciones configurables.
  • Cifrado AEAD: Cifrado autenticado seguro con AES-GCM y derivación de clave PBKDF2.
  • Hashing: Soporte para SHA-2, SHA-3, BLAKE2b, BLAKE2s y BLAKE3. MD5 y SHA-1 siguen disponibles como opciones obsoletas por compatibilidad.
  • HMAC / Hash con clave: Soporte para HMAC-SHA2 y BLAKE2b con clave.

Frameworks soportados

  • net8.0
  • net9.0
  • net10.0

Ejemplos prácticos rápidos

Registrar la contraseña de un usuario
using Pitasoft.Safety;

var plainPassword = "MyStr0ngP@ss!";
var storedHash = PasswordHasher.Create(plainPassword);

// Guarda storedHash en tu base de datos
Validar credenciales de inicio de sesión
using Pitasoft.Safety;

var inputPassword = "MyStr0ngP@ss!";
var storedHash = GetPasswordHashFromDatabase();

if (PasswordHasher.Verify(inputPassword, storedHash))
{
    Console.WriteLine("Login OK");
}
else
{
    Console.WriteLine("Credenciales inválidas");
}
Generar una contraseña que cumpla tu política
using Pitasoft.Safety;

var policy = new PasswordOption
{
    RequiredLength = 16,
    RequiredUniqueChars = 6,
    RequireUppercase = true,
    RequireLowercase = true,
    RequireDigit = true,
    RequireNonAlphanumeric = true
};

var generatedPassword = Password.Generate(policy);
var isValid = Password.IsValid(generatedPassword, policy);
Cifrar y descifrar datos de aplicación con contraseña
using Pitasoft.Safety;

var token = SecureCrypt.EncryptAead("ConnectionStringOrSecret", "master-password");
var original = SecureCrypt.DecryptAead(token, "master-password");
Calcular una huella y firmar un payload
using System.Text;
using Pitasoft.Safety;
using Pitasoft.Safety.Extensions;

var fingerprint = "document-content".Hash(AlgorithmType.Sha256, "tenant-a");
var macKey = Encoding.UTF8.GetBytes("shared-secret-key");
var signature = "payload-to-protect".Hmac(HmacAlgorithmType.HmacSha256, macKey);

Referencia de API y Ejemplos

1. Gestión de Contraseñas (Password y PasswordOption)

Proporciona métodos para generar y validar contraseñas.

  • Password.Generate(PasswordOption? option = null): Genera una contraseña aleatoria criptográficamente segura.
  • Lanza una excepción si la política configurada es imposible de cumplir, por ejemplo si los caracteres únicos requeridos superan la longitud pedida.
  • Password.IsValid(string? password, PasswordOption? option = null): Valida si una contraseña cumple con los requisitos.
  • PasswordOption: Define las reglas de contraseña. Por defecto usa longitud 6, 1 carácter único y todas las categorías activadas.

Ejemplo:

using Pitasoft.Safety;

var options = new PasswordOption 
{ 
    RequiredLength = 12, 
    RequiredUniqueChars = 4,
    RequireUppercase = true,
    RequireLowercase = true,
    RequireDigit = true,
    RequireNonAlphanumeric = true
};

string password = Password.Generate(options);
bool esValida = Password.IsValid(password, options);
2. Hash de Contraseñas (PasswordHasher)

Almacenamiento seguro de contraseñas mediante PBKDF2.

Usa esta API para contraseñas de usuario. Los helpers genéricos Hash(...) están pensados para huellas y escenarios que no sean almacenamiento de passwords.

  • PasswordHasher.Create(string password, int iterations = 200000): Crea un token de hash seguro (pbkdf2-v1$iter$salt$hash).
  • PasswordHasher.Verify(string password, string token): Verifica una contraseña contra un token de hash.
  • Devuelve false si el token es inválido o está mal formado.

Ejemplo:

string hash = PasswordHasher.Create("mi-password");
bool verificado = PasswordHasher.Verify("mi-password", hash);
3. Cifrado AEAD (SecureCrypt)

API de alto nivel para cifrado AES-GCM con derivación de clave basada en contraseña o clave directa.

  • SecureCrypt.EncryptAead(string plaintext, string password, int iterations = 200000): Cifra texto usando una clave derivada de una contraseña (PBKDF2).
  • SecureCrypt.DecryptAead(string token, string password): Descifra un token versionado usando una clave derivada de una contraseña.
  • SecureCrypt.EncryptAeadWithKey(string plaintext, ReadOnlySpan<byte> key, ReadOnlySpan<byte> salt, int iterations): Cifra texto usando una clave criptográfica directa e incluye el salt/iteraciones en el token para su posterior descifrado.
  • SecureCrypt.DecryptAeadWithKey(string token, ReadOnlySpan<byte> key): Descifra un token versionado usando una clave criptográfica directa.

Ejemplo (Basado en contraseña):

string token = SecureCrypt.EncryptAead("mi mensaje secreto", "password-seguro");
string descifrado = SecureCrypt.DecryptAead(token, "password-seguro");

Ejemplo (Clave Directa):

byte[] key = System.Security.Cryptography.RandomNumberGenerator.GetBytes(32);
byte[] salt = System.Security.Cryptography.RandomNumberGenerator.GetBytes(16);
string token = SecureCrypt.EncryptAeadWithKey("confidencial", key, salt, 200000);
string descifrado = SecureCrypt.DecryptAeadWithKey(token, key);
4. Extensiones (Pitasoft.Safety.Extensions)

Métodos de extensión convenientes para strings.

  • Extensions.ChangeKey(string key): Establece la clave de cifrado global. Conviene configurarla una sola vez al arrancar la aplicación.
  • str.Encrypt() / str.Decrypt(): Cifra/Descifra usando la clave global.
  • str.EncryptKey(string key) / str.DecryptKey(string key): Cifra/Descifra usando una clave específica.
  • str.Hash(AlgorithmType type, string salt = ""): Genera un hash. Soporta Md5 y Sha1 como opciones obsoletas, además de Sha256, Sha384, Sha512, Sha3_256, Sha3_512, Blake2b_256, Blake2b_512, Blake2s_256 y Blake3. Está pensado para huellas, no para almacenar contraseñas.
  • str.Hmac(HmacAlgorithmType type, byte[] key): Genera un HMAC o hash con clave. Soporta HmacSha256, HmacSha384, HmacSha512, Blake2b_256 y Blake2b_512.

Nota de compatibilidad: cuando se proporciona salt, la librería ahora codifica el valor y el salt como campos separados antes de calcular el hash. Esto evita colisiones por concatenación ambigua y cambia el resultado respecto a versiones anteriores para el mismo par (input, salt).

Nota: los valores Blake2b_* de HmacAlgorithmType corresponden a hashes BLAKE2b con clave, no a una construcción HMAC estándar.

5. Enumeraciones públicas
  • AlgorithmType: Selecciona el algoritmo de hash usado por Hash(...).
  • HmacAlgorithmType: Selecciona el algoritmo HMAC o hash con clave usado por Hmac(...).
  • TypeCharacter: Enumeración pública que representa categorías de caracteres de contraseña.

Ejemplo:

using Pitasoft.Safety.Extensions;

// Hashing
string sha512 = "hola".Hash(AlgorithmType.Sha512);
string blake3 = "hola".Hash(AlgorithmType.Blake3);

// HMAC
byte[] llave = System.Text.Encoding.UTF8.GetBytes("clave-secreta");
string hmac = "mensaje".Hmac(HmacAlgorithmType.HmacSha256, llave);

Autor

Sebastián Martínez Pérez

License

Copyright © 2019-2026 Pitasoft, S.L. Licensed under the LICENSE.txt provided in this repository.

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 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 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

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
7.1.1 117 4/1/2026
7.0.1 115 2/23/2026
6.0.0 343 8/21/2024
5.1.2 499 12/15/2023
5.1.1 263 12/15/2023
5.1.0 323 11/20/2023
5.0.0 317 9/8/2023
4.1.1 452 2/21/2023
4.1.0 496 1/23/2023
4.0.0 499 1/14/2023
3.2.0 546 11/18/2022
3.1.0 595 7/26/2022
3.0.0 509 12/27/2021
2.0.0 613 6/26/2021
1.0.1 675 9/30/2020
1.0.0 692 9/14/2020