SatCredentialsNet 1.0.0

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

SatCredentialsNet

.NET .NET .NET NuGet Version NuGet Downloads License: MIT

SatCredentialsNet es una librería .NET para trabajar con certificados del SAT (Servicio de Administración Tributaria) de México, incluyendo certificados CSD (Certificado de Sello Digital) y FIEL/e.firma.

Soporta carga, validación, extracción de datos, encriptación, firma digital y exportación de claves. Compatible con .NET 8, 9, 10 sobre Windows, Linux y macOS.


Características

  • Carga de certificados .cer y llaves privadas .key (PKCS#8 DER encriptado) desde archivos, bytes o streams.
  • Validaciones automáticas al inicializar:
    • Vigencia del certificado.
    • Correspondencia entre certificado y llave privada.
    • Emisor: Servicio de Administración Tributaria (SAT).
  • Extracción de datos del certificado:
    • RFC, RFC del representante legal (personas morales).
    • CURP, CURP del representante legal.
    • Razón social, nombre de sucursal, email y número de serie.
    • Tipo de persona (física o moral) y tipo de certificado (CSD o FIEL).
  • Operaciones criptográficas:
    • Firma y verificación con SHA256 y SHA1.
    • Encriptación y desencriptación RSA PKCS#1.
  • Exportación de claves y certificados en múltiples formatos: PEM, DER, Base64, PKCS#8, PFX.

Instalación

dotnet add package SatCredentialsNet

Uso básico

using SatCredentialsNet;
using System.Text;

// Desde archivos
using var credentials = new SatCredentials("cert.cer", "private_key.key", "contraseña");

// Desde bytes
var cerBytes = File.ReadAllBytes("cert.cer");
var keyBytes = File.ReadAllBytes("private_key.key");
using var credentials = new SatCredentials(cerBytes, keyBytes, "contraseña");

// Desde streams
using var cerStream = File.OpenRead("cert.cer");
using var keyStream = File.OpenRead("private_key.key");
using var credentials = new SatCredentials(cerStream, keyStream, "contraseña");

// Datos del contribuyente
Console.WriteLine($"RFC:          {credentials.Rfc}");
Console.WriteLine($"Razón social: {credentials.RazonSocial}");
Console.WriteLine($"Tipo:         {credentials.TipoCertificado}"); // CSD o FIEL
Console.WriteLine($"Persona:      {credentials.TipoPersona}");     // FISICA o MORAL
Console.WriteLine($"Vigente:      {credentials.IsInForce}");
Console.WriteLine($"Válido hasta: {credentials.ValidTo:yyyy-MM-dd}");

Nota: SatCredentials implementa IDisposable. Usa using o llama a Dispose() para liberar correctamente los recursos criptográficos.


Constructores

Constructor Descripción
SatCredentials(byte[] cert, byte[] key, string password) Carga desde arreglos de bytes.
SatCredentials(string certPath, string keyPath, string password) Carga desde rutas de archivos.
SatCredentials(Stream cert, Stream key, string password) Carga desde streams.

En todos los casos se valida automáticamente que:

  1. El certificado sea legible y con formato válido.
  2. La contraseña sea correcta y la llave privada sea descifrable.
  3. La llave privada corresponda al certificado.
  4. El certificado esté vigente.
  5. El emisor sea el SAT.

Propiedades

Datos del contribuyente

Propiedad Tipo Descripción
Rfc string RFC del titular del certificado.
RfcRepresentanteLegal string RFC del representante legal (personas morales). Vacío si no aplica.
Curp string CURP del titular.
CurpRepresentanteLegal string CURP del representante legal. Vacío si no aplica.
RazonSocial string Nombre o razón social del titular (sin régimen societario).
NombreSucursal string Nombre de la sucursal (campo OU del certificado).
Email string Correo electrónico registrado en el certificado.
TipoPersona TaxpayerType FISICA (RFC de 13 caracteres) o MORAL (RFC de 12 caracteres).
TipoCertificado CertificateType CSD (Certificado de Sello Digital) o FIEL (e.firma).

Datos del certificado

Propiedad Tipo Descripción
SerialNumber string Número de serie del certificado.
Version int Versión del certificado X.509 (generalmente 3).
ValidFrom DateTime Fecha de inicio de vigencia (UTC).
ValidTo DateTime Fecha de fin de vigencia (UTC).
IsInForce bool true si el certificado está vigente en este momento.
Subject string Cadena completa del Subject del certificado.
Issuer string Cadena completa del Issuer del certificado.

Claves y exportaciones

Propiedad Tipo Descripción
PublicKey RSA Instancia RSA de la clave pública.
PrivateKey RSA Instancia RSA de la clave privada.
PublicKeyBytes byte[] Bytes DER de la clave pública (del certificado).
PublicKeyString string Representación hexadecimal de la clave pública.
PublicKeyPem string Clave pública en formato PEM (BEGIN PUBLIC KEY).
RSAPublicKeyPem string Clave pública RSA en formato PEM (BEGIN RSA PUBLIC KEY).
PublicKeyBytesFromPrivateKey byte[] Bytes de la clave pública extraída desde la clave privada.
PublicKeyPemFromPrivateKey string PEM de la clave pública extraída desde la clave privada.
PrivateKeyBytes byte[] Bytes DER de la clave privada (formato PKCS#1).
RSAPrivateKeyPem string Clave privada en formato PEM PKCS#1 (BEGIN RSA PRIVATE KEY).
Pkcs8PrivateKeyPem string Clave privada en formato PEM PKCS#8 (BEGIN PRIVATE KEY).
CertificatePem string Certificado completo en formato PEM.
CertificateB64 string Certificado en Base64 (requerido por algunos servicios del SAT).
Pfx byte[] Certificado + clave privada empaquetados en formato PFX/PKCS#12.

Métodos

Encriptación / Desencriptación

byte[] Encrypt(byte[] data)
byte[] Decrypt(byte[] data)

Usa RSA con padding PKCS#1. La encriptación se realiza con la clave pública y la desencriptación con la clave privada.

var data = Encoding.UTF8.GetBytes("Datos confidenciales");
var encrypted = credentials.Encrypt(data);
var decrypted = credentials.Decrypt(encrypted);

Firma digital

byte[] SingSHA256(byte[] data)
byte[] SingSHA1(byte[] data)

Firma los datos con la clave privada usando PKCS#1 y el algoritmo indicado. SHA256 es el estándar requerido para la generación de sellos digitales en CFDI.

var cadena = Encoding.UTF8.GetBytes("||cadena original||");
var sello = credentials.SingSHA256(cadena);
var selloBase64 = Convert.ToBase64String(sello);

Verificación de firma

bool VerifySHA256(byte[] data, byte[] signature)
bool VerifySHA1(byte[] data, byte[] signature)

Verifica que la firma corresponda a los datos usando la clave pública.

var esValido = credentials.VerifySHA256(cadena, sello);
Console.WriteLine($"Firma válida: {esValido}");

Manejo de errores

Todas las excepciones lanzadas por la librería son del tipo SatCredentialsError, que extiende Exception e incluye un código de error tipado.

try
{
    using var credentials = new SatCredentials(cerBytes, keyBytes, password);
}
catch (SatCredentialsError ex)
{
    Console.WriteLine($"Error {ex.ErrorCode}: {ex.Message}");
    // Ejemplo: "[1007] CertificateExpired: The certificate is expired."
}

Códigos de error

Código Valor Descripción
CertificateError 1000 El certificado no pudo ser leído (formato inválido o corrupto).
CertificateEmpty 1001 Los bytes del certificado están vacíos.
PrivateKeyEmpty 1002 Los bytes de la llave privada están vacíos.
MissingPassword 1003 La contraseña de la llave privada está vacía o es nula.
PrivateKeyIncorrectPassword 1004 La contraseña es incorrecta y no se pudo descifrar la llave privada.
CertificateWithoutPublicKey 1005 El certificado no contiene una clave pública.
CertificateAndPrivateKeyMismatch 1006 El certificado y la llave privada no corresponden entre sí.
CertificateExpired 1007 El certificado no está vigente.
CertificateNotFromSat 1008 El emisor del certificado no es el SAT.

Enumeraciones

SatCredentialsConstants.CertificateType

Valor Descripción
CSD Certificado de Sello Digital (para timbrado de CFDI).
FIEL Firma Electrónica Avanzada / e.firma (para autenticación ante el SAT).

SatCredentialsConstants.TaxpayerType

Valor Descripción
FISICA Persona física (RFC de 13 caracteres).
MORAL Persona moral (RFC de 12 caracteres).

Ejemplo completo: Generar sello para CFDI

using SatCredentialsNet;
using System.Text;

using var credentials = new SatCredentials(
    "/ruta/al/certificado.cer",
    "/ruta/a/la/llave.key",
    "contraseña_llave"
);

Console.WriteLine($"RFC:             {credentials.Rfc}");
Console.WriteLine($"Tipo:            {credentials.TipoCertificado}");
Console.WriteLine($"No. Certificado: {credentials.SerialNumber}");
Console.WriteLine($"Certificado:     {credentials.CertificateB64}");

// Generar sello digital SHA256
var cadenaOriginal = "||cadena original del CFDI||";
var selloBytes = credentials.SingSHA256(Encoding.UTF8.GetBytes(cadenaOriginal));
var sello = Convert.ToBase64String(selloBytes);

Console.WriteLine($"Sello: {sello}");

Requisitos

  • Certificado en formato DER (.cer binario descargado del SAT, no PEM).
  • Llave privada en formato PKCS#8 DER encriptado (.key binario descargado del SAT).

Compatibilidad

Framework Soporte
.NET 8
.NET 9
.NET 10

Plataformas: Windows, Linux, macOS.


Licencia

Este proyecto está bajo la licencia MIT.

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

    • No dependencies.
  • net8.0

    • No dependencies.
  • net9.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
1.0.0 111 4/24/2026