EncryptionPacketIds 1.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package EncryptionPacketIds --version 1.0.0
                    
NuGet\Install-Package EncryptionPacketIds -Version 1.0.0
                    
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="EncryptionPacketIds" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="EncryptionPacketIds" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="EncryptionPacketIds" />
                    
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 EncryptionPacketIds --version 1.0.0
                    
#r "nuget: EncryptionPacketIds, 1.0.0"
                    
#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 EncryptionPacketIds@1.0.0
                    
#: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=EncryptionPacketIds&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=EncryptionPacketIds&version=1.0.0
                    
Install as a Cake Tool

PaqueteDeEncriptacion

Una librería .NET ligera y segura para encriptar y desencriptar IDs utilizando AES-256.

Características

  • Seguridad robusta: Usa encriptación AES-256 (estándar militar)
  • Fácil de usar: API simple e intuitiva
  • Soporte múltiples tipos: Encripta IDs de tipo int, long y string
  • Flexible: Usa tu propia clave o genera una automáticamente
  • Bien probado: Incluye suite completa de pruebas unitarias
  • Open Source: Licencia MIT

Instalación

Desde NuGet (cuando esté publicado)

dotnet add package PaqueteDeEncriptacion

Desde el código fuente

git clone https://github.com/tu-usuario/PaqueteDeEncriptacion.git
cd PaqueteDeEncriptacion
dotnet build

Uso Rápido

Ejemplo básico con string como clave

using PaqueteDeEncriptacion;

// Crear instancia con una clave secreta
var encryptor = new IdEncryptor("MiClaveSecreta123!");

// Encriptar un ID
int userId = 12345;
string encryptedId = encryptor.Encrypt(userId);
Console.WriteLine($"ID encriptado: {encryptedId}");
// Salida: ID encriptado: a8f5e3d2c1b4... (Base64)

// Desencriptar el ID
int decryptedId = encryptor.DecryptToInt(encryptedId);
Console.WriteLine($"ID desencriptado: {decryptedId}");
// Salida: ID desencriptado: 12345

Encriptar diferentes tipos de IDs

var encryptor = new IdEncryptor("MiClaveSecreta123!");

// Encriptar int
int idInt = 100;
string encryptedInt = encryptor.Encrypt(idInt);
int decryptedInt = encryptor.DecryptToInt(encryptedInt);

// Encriptar long
long idLong = 9876543210L;
string encryptedLong = encryptor.Encrypt(idLong);
long decryptedLong = encryptor.DecryptToLong(encryptedLong);

// Encriptar string
string idString = "ABC-123-XYZ";
string encryptedString = encryptor.Encrypt(idString);
string decryptedString = encryptor.Decrypt(encryptedString);

Uso avanzado con claves personalizadas

// Generar clave e IV aleatorios
byte[] key = IdEncryptor.GenerateKey();    // 32 bytes (256 bits)
byte[] iv = IdEncryptor.GenerateIV();      // 16 bytes (128 bits)

// Guardar la clave de forma segura (ej: en configuración, vault, etc.)
string keyBase64 = Convert.ToBase64String(key);
string ivBase64 = Convert.ToBase64String(iv);

// Crear encryptor con la clave personalizada
var encryptor = new IdEncryptor(key, iv);

// Usar normalmente
string encrypted = encryptor.Encrypt(42);
int decrypted = encryptor.DecryptToInt(encrypted);

Ejemplo en una API Web (ASP.NET Core)

// Startup.cs o Program.cs
builder.Services.AddSingleton<IdEncryptor>(sp =>
{
    var secretKey = builder.Configuration["Encryption:SecretKey"];
    return new IdEncryptor(secretKey);
});

// En tu controlador
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
    private readonly IdEncryptor _encryptor;

    public UsersController(IdEncryptor encryptor)
    {
        _encryptor = encryptor;
    }

    [HttpGet("{encryptedId}")]
    public IActionResult GetUser(string encryptedId)
    {
        try
        {
            int userId = _encryptor.DecryptToInt(encryptedId);
            // Usar userId para buscar en base de datos...
            return Ok(new { UserId = userId });
        }
        catch (Exception ex)
        {
            return BadRequest("ID inválido");
        }
    }

    [HttpPost]
    public IActionResult CreateUser([FromBody] CreateUserRequest request)
    {
        // Crear usuario y obtener ID de base de datos
        int newUserId = 12345; // Ejemplo

        // Encriptar el ID antes de devolverlo
        string encryptedId = _encryptor.Encrypt(newUserId);

        return Ok(new { EncryptedId = encryptedId });
    }
}

API Reference

Constructores

IdEncryptor(string secretKey)

Crea una instancia usando un string como clave secreta.

  • Parámetros:
    • secretKey: La clave secreta (puede ser cualquier string)
  • Ejemplo: new IdEncryptor("MiClave123")
IdEncryptor(byte[] key, byte[] iv)

Crea una instancia con clave e IV personalizados.

  • Parámetros:
    • key: Array de 32 bytes (256 bits)
    • iv: Array de 16 bytes (128 bits)
  • Ejemplo: new IdEncryptor(key, iv)

Métodos de Encriptación

string Encrypt(int id)

Encripta un ID de tipo int.

  • Retorna: String en formato Base64
string Encrypt(long id)

Encripta un ID de tipo long.

  • Retorna: String en formato Base64
string Encrypt(string id)

Encripta un ID de tipo string.

  • Retorna: String en formato Base64

Métodos de Desencriptación

int DecryptToInt(string encryptedId)

Desencripta y convierte a int.

  • Parámetros: encryptedId - ID encriptado en Base64
  • Retorna: int desencriptado
  • Excepciones: FormatException si no es un int válido
long DecryptToLong(string encryptedId)

Desencripta y convierte a long.

  • Parámetros: encryptedId - ID encriptado en Base64
  • Retorna: long desencriptado
  • Excepciones: FormatException si no es un long válido
string Decrypt(string encryptedId)

Desencripta a string.

  • Parámetros: encryptedId - ID encriptado en Base64
  • Retorna: string desencriptado

Métodos Estáticos (Utilidades)

static byte[] GenerateKey()

Genera una clave aleatoria de 32 bytes para AES-256.

  • Retorna: Array de 32 bytes
static byte[] GenerateIV()

Genera un IV aleatorio de 16 bytes.

  • Retorna: Array de 16 bytes

Seguridad

Buenas Prácticas

  1. Nunca hardcodees la clave en el código

    // MAL
    var encryptor = new IdEncryptor("clave123");
    
    // BIEN
    var secretKey = Environment.GetEnvironmentVariable("ENCRYPTION_KEY");
    var encryptor = new IdEncryptor(secretKey);
    
  2. Usa variables de entorno o servicios de gestión de secretos

    // appsettings.json
    {
      "Encryption": {
        "SecretKey": "TuClaveSecretaAquí"
      }
    }
    
    // En código
    var key = configuration["Encryption:SecretKey"];
    
  3. Mantén la clave en un lugar seguro

    • Azure Key Vault
    • AWS Secrets Manager
    • Variables de entorno
    • Archivos de configuración (NO commitear a git)
  4. Usa una clave diferente para cada ambiente

    • Desarrollo: Una clave
    • Testing: Otra clave
    • Producción: Clave diferente y más segura

Algoritmo

Esta librería usa:

  • AES-256: Encriptación simétrica (256 bits)
  • CBC Mode: Cipher Block Chaining
  • PKCS7 Padding: Relleno estándar

Casos de Uso

  • Ocultar IDs de base de datos en URLs
  • Proteger IDs de usuarios en APIs públicas
  • Prevenir enumeración de recursos
  • Ofuscar identificadores en frontend
  • Compartir IDs sensibles de forma segura

Contribuir

Las contribuciones son bienvenidas! Por favor:

  1. Haz fork del proyecto
  2. Crea una rama para tu feature (git checkout -b feature/AmazingFeature)
  3. Commit tus cambios (git commit -m 'Add some AmazingFeature')
  4. Push a la rama (git push origin feature/AmazingFeature)
  5. Abre un Pull Request

Ejecutar Pruebas

dotnet test

Licencia

Este proyecto está bajo la Licencia MIT. Ver el archivo LICENSE para más detalles.

Autor

ING. Luis Luna

Soporte

Si encuentras algún problema o tienes sugerencias, por favor abre un issue.


Hecho con ❤️ para la comunidad .NET

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.
  • net8.0

    • No dependencies.

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
2.0.1 227 12/21/2025
2.0.0 285 12/17/2025
1.0.0 231 12/14/2025

v1.0.0:
- AES-256-GCM encryption for IDs
- Supports int, long and string identifiers
- Secure non-deterministic encryption (random nonce)
- Simple and intuitive API
- Production-ready