Referencia Pública de API .NETL3 Persistencia e IntegracionesEstableAOT: Parcial

EricksonLopez.Security

High-performance, Native AOT-first cryptographic foundation, multi-version key lifecycle manager, password security engine, and Zero Trust authorization ecosystem for modern .NET.

77 namespaces365 tipos2030 miembrosGenerado desde XML docs y ensamblados · UTC 2026-12-01

Mostrando 365 de 365 tipos (2030 miembros)

EricksonLopez.Security.Abstractions.Authorization#

4
interface

IGenerationalPermissionCache

Ensamblado: EricksonLopez.Security.Abstractions
public interface IGenerationalPermissionCache

Defines a two-tier (L1 in-memory + L2 distributed epoch-keyed) stampede-protected permission cache with strict fail-closed semantics (`PermissionSnapshot.Deny`) upon backing store or cache outages.

Miembros (5)

  • methodGetEffectiveSnapshotAsync
    ValueTask<PermissionSnapshot> GetEffectiveSnapshotAsync(PermissionScopeKey key, CancellationToken cancellationToken = default)

    Resolves the effective `PermissionSnapshot` for `key` using generational L1+L2 caching, bypassing caches for delegated/impersonated sessions, and returning `PermissionSnapshot.Deny` on failure.

    key: PermissionScopeKey
    The multi-plane permission scope key.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A value task containing the effective `PermissionSnapshot`.

  • methodInvalidateLocalGeneration
    void InvalidateLocalGeneration()

    Immediately bumps the local L1 in-memory generation counter so subsequent reads re-verify against L2 epochs.

  • methodInvalidatePrincipalAsync
    ValueTask InvalidatePrincipalAsync(string principalId, CancellationToken cancellationToken = default)

    Atomically bumps the L1 generation and the L2 principal epoch for `principalId`, immediately invalidating all cached snapshots for that user or service principal without `SCAN` operations.

    principalId: string
    The user or service principal identifier to invalidate.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A value task representing the invalidation operation.

  • methodInvalidatePrincipalsAsync
    ValueTask InvalidatePrincipalsAsync(IEnumerable<string> principalIds, CancellationToken cancellationToken = default)

    Atomically bumps the L1 generation and the L2 principal epochs for a batch of `principalIds` (for example, after a role mutation).

    principalIds: IEnumerable<string>
    The principal identifiers to invalidate.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A value task representing the batch invalidation operation.

  • methodInvalidateTenantAsync
    ValueTask InvalidateTenantAsync(string tenantId, CancellationToken cancellationToken = default)

    Atomically bumps the L1 generation and the L2 tenant epoch for `tenantId`, immediately invalidating all cached snapshots across the entire tenant in O(1) time.

    tenantId: string
    The tenant identifier to invalidate.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A value task representing the invalidation operation.

interface

IPermissionSnapshotSource

Ensamblado: EricksonLopez.Security.Abstractions
public interface IPermissionSnapshotSource

Defines the authoritative persistence data source used by `IGenerationalPermissionCache` on L1+L2 cache misses or live delegated session evaluations.

Miembros (1)

  • methodResolveSnapshotAsync
    ValueTask<PermissionSnapshot> ResolveSnapshotAsync(PermissionScopeKey key, CancellationToken cancellationToken = default)

    Resolves the authoritative `PermissionSnapshot` for `key` from the backing store.

    key: PermissionScopeKey
    The multi-plane permission scope key.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A value task producing the resolved `PermissionSnapshot`.

record

PermissionScopeKey

Ensamblado: EricksonLopez.Security.Abstractions
public sealed record PermissionScopeKey(SecurityPlane Plane, string PrincipalId, string? TenantId, string? CompanyId, string? DelegationSessionId)

Identifies the exact multi-plane security scope for resolving and caching a `PermissionSnapshot`.

Miembros (7)

  • constructorPermissionScopeKey
    public PermissionScopeKey(SecurityPlane Plane, string PrincipalId, string? TenantId = null, string? CompanyId = null, string? DelegationSessionId = null)

    Initializes a new instance of PermissionScopeKey.

    Plane: SecurityPlane
    The execution `SecurityPlane` (`Control`, `Tenant`, or `Service`).
    PrincipalId: string
    The user identifier (human planes) or service principal identifier (`Service` plane).
    TenantId: string?
    Optional tenant identifier (mandatory for `SecurityPlane.Tenant` and `SecurityPlane.Service`).
    CompanyId: string?
    Optional organization unit / company identifier.
    DelegationSessionId: string?
    Optional support delegation or impersonation session identifier. When non-empty, caches must be bypassed so revocation is evaluated live.
  • propertyCompanyId
    public string? CompanyId { get; init; }

    Optional organization unit / company identifier.

  • propertyDelegationSessionId
    public string? DelegationSessionId { get; init; }

    Optional support delegation or impersonation session identifier. When non-empty, caches must be bypassed so revocation is evaluated live.

  • propertyPlane
    public SecurityPlane Plane { get; init; }

    The execution `SecurityPlane` (`Control`, `Tenant`, or `Service`).

  • propertyPrincipalId
    public string PrincipalId { get; init; }

    The user identifier (human planes) or service principal identifier (`Service` plane).

  • propertyRequiresLiveEvaluation
    public bool RequiresLiveEvaluation { get; }

    Gets a value indicating whether this scope represents a live delegated/impersonated session that must bypass L1/L2 caching.

  • propertyTenantId
    public string? TenantId { get; init; }

    Optional tenant identifier (mandatory for `SecurityPlane.Tenant` and `SecurityPlane.Service`).

record

PermissionSnapshot

Ensamblado: EricksonLopez.Security.Abstractions
public sealed record PermissionSnapshot(bool IsPrincipalActive, bool IsContextActive, IReadOnlyList<string> RoleCodes, IReadOnlySet<string> Permissions, IReadOnlySet<string> StepUpPermissions, string PermissionsHash)

Represents an immutable, effective authorization snapshot for a principal within a specific security plane and scope, supporting deterministic permission hashing and fail-closed default denial.

Miembros (10)

  • constructorPermissionSnapshot
    public PermissionSnapshot(bool IsPrincipalActive, bool IsContextActive, IReadOnlyList<string> RoleCodes, IReadOnlySet<string> Permissions, IReadOnlySet<string> StepUpPermissions, string PermissionsHash)

    Initializes a new instance of PermissionSnapshot.

    IsPrincipalActive: bool
    Indicates whether the underlying human or service principal account is active and non-deleted.
    IsContextActive: bool
    Indicates whether the active tenant, organization unit, or delegation session is active.
    RoleCodes: IReadOnlyList<string>
    Ordered list of active role codes assigned in the evaluated scope.
    Permissions: IReadOnlySet<string>
    Case-insensitive set of effective granted permission codes.
    StepUpPermissions: IReadOnlySet<string>
    Case-insensitive subset of `Permissions` requiring step-up MFA assurance (`AAL2+`).
    PermissionsHash: string
    Deterministic 64-character lowercase SHA-256 hex digest of the sorted effective permission codes.
  • methodComputePermissionsHash
    public static string ComputePermissionsHash(IEnumerable<string> permissions)

    Computes the canonical 64-character lowercase hexadecimal SHA-256 digest of a permission set sorted ordinally.

    permissions: IEnumerable<string>
    The permission strings to hash.

    Retorna: The 64-character lowercase hexadecimal SHA-256 digest.

  • methodCreate
    public static PermissionSnapshot Create(bool isPrincipalActive, bool isContextActive, IReadOnlyList<string>? roleCodes = null, IEnumerable<string>? permissions = null, IEnumerable<string>? stepUpPermissions = null, IEnumerable<string>? forbiddenPermissionsToStrip = null)

    Builds a normalized `PermissionSnapshot`, stripping all permissions when either principal or context is inactive, optionally stripping delegation-forbidden permissions, and computing the canonical sorted SHA-256 `PermissionsHash`.

    isPrincipalActive: bool
    Whether the principal account is active.
    isContextActive: bool
    Whether the tenant/company/delegation context is active.
    roleCodes: IReadOnlyList<string>?
    Optional role codes granted in the scope.
    permissions: IEnumerable<string>?
    Optional granted permission codes.
    stepUpPermissions: IEnumerable<string>?
    Optional permission codes requiring elevated MFA assurance.
    forbiddenPermissionsToStrip: IEnumerable<string>?
    Optional set of permissions to strip (for example, during support delegation/impersonation).

    Retorna: A normalized `PermissionSnapshot`.

  • propertyDeny
    public static PermissionSnapshot Deny { get; }

    Gets a canonical fail-closed snapshot denying all access (`IsPrincipalActive = false`, `IsContextActive = false`, empty permissions).

  • propertyIsContextActive
    public bool IsContextActive { get; init; }

    Indicates whether the active tenant, organization unit, or delegation session is active.

  • propertyIsPrincipalActive
    public bool IsPrincipalActive { get; init; }

    Indicates whether the underlying human or service principal account is active and non-deleted.

  • propertyPermissions
    public IReadOnlySet<string> Permissions { get; init; }

    Case-insensitive set of effective granted permission codes.

  • propertyPermissionsHash
    public string PermissionsHash { get; init; }

    Deterministic 64-character lowercase SHA-256 hex digest of the sorted effective permission codes.

  • propertyRoleCodes
    public IReadOnlyList<string> RoleCodes { get; init; }

    Ordered list of active role codes assigned in the evaluated scope.

  • propertyStepUpPermissions
    public IReadOnlySet<string> StepUpPermissions { get; init; }

    Case-insensitive subset of `Permissions` requiring step-up MFA assurance (`AAL2+`).

EricksonLopez.Security.Abstractions.Cryptography#

9
enum

AeadAlgorithm

Ensamblado: EricksonLopez.Security.Abstractions
public enum AeadAlgorithm : byte

Specifies the Authenticated Encryption with Associated Data (AEAD) algorithm.

Miembros (3)

  • fieldAes256Gcm
    Aes256Gcm = 1

    Specifies the Advanced Encryption Standard with Galois/Counter Mode (AES-256-GCM) per NIST SP 800-38D. Uses 256-bit keys, 96-bit (12-byte) nonces, and 128-bit (16-byte) authentication tags.

  • fieldChaCha20Poly1305
    ChaCha20Poly1305 = 2

    Specifies the ChaCha20 stream cipher with Poly1305 authenticator per RFC 8439. Uses 256-bit keys, 96-bit (12-byte) nonces, and 128-bit (16-byte) authentication tags.

  • fieldHkdfAes256Gcm
    HkdfAes256Gcm = 3

    Specifies the HKDF-Enhanced AES-256-GCM AEAD scheme providing per-operation key isolation.

struct

AuthenticatedContext

Ensamblado: EricksonLopez.Security.Abstractions
public readonly struct AuthenticatedContext : IEquatable<AuthenticatedContext>
Implementa: IEquatable<AuthenticatedContext>

Provides a strongly-typed cryptographic context used as Authenticated Associated Data (AAD) in Authenticated Encryption with Associated Data (AEAD) schemes.

Miembros (13)

  • methodEquals
    public bool Equals(AuthenticatedContext other)

    Inherits documentation from base type or interface.

    other: AuthenticatedContext
  • methodEquals
    public override bool Equals(object? obj)

    Inherits documentation from base type or interface.

    obj: object?
  • methodForPurpose
    public static AuthenticatedContext ForPurpose(string domain, string purpose, params(string Key, string Value)[] bindings)

    Creates a canonical UTF-8 authenticated context bound to an application domain, cryptographic purpose, and ordered key-value context bindings (`{domain}|v1|purpose:{purpose}|{key}:{value}...`).

    domain: string
    The application or platform domain namespace (for example, `"platform"`).
    purpose: string
    The cryptographic purpose identifier (for example, `"TOTP_SECRET"`).
    bindings: params(string Key, string Value)[]
    Ordered key-value bindings identifying the owning security scope.

    Retorna: A strongly-typed `AuthenticatedContext`.

    Exceptions: ArgumentException: `domain`, `purpose`, or any binding key/value is null or whitespace.; ArgumentNullException: `bindings` is `null`.

  • methodForTenant
    public static AuthenticatedContext ForTenant(string tenantId)

    Creates an authenticated context bound to a specific tenant identifier.

    tenantId: string
    The unique identifier of the tenant.

    Retorna: A strongly-typed authenticated context.

    Exceptions: ArgumentException: `tenantId` is `null` or whitespace

  • methodForTenantSecret
    public static AuthenticatedContext ForTenantSecret(string domain, string purpose, string tenantId, string companyId)

    Creates a canonical UTF-8 authenticated context bound to a tenant and company scope (`{domain}|v1|purpose:{purpose}|tenant:{tenantId}|company:{companyId}`).

    domain: string
    The application or platform domain namespace.
    purpose: string
    The cryptographic secret purpose.
    tenantId: string
    The non-empty tenant identifier.
    companyId: string
    The non-empty company or organization unit identifier.

    Retorna: A strongly-typed `AuthenticatedContext`.

    Exceptions: ArgumentException: Any argument is null or whitespace.

  • methodForUserSecret
    public static AuthenticatedContext ForUserSecret(string domain, string purpose, string userId)

    Creates a canonical UTF-8 authenticated context bound to a specific user secret (`{domain}|v1|purpose:{purpose}|user:{userId}`).

    domain: string
    The application or platform domain namespace.
    purpose: string
    The cryptographic secret purpose.
    userId: string
    The non-empty user identifier.

    Retorna: A strongly-typed `AuthenticatedContext`.

    Exceptions: ArgumentException: Any argument is null or whitespace.

  • methodFromBytes
    public static AuthenticatedContext FromBytes(ReadOnlySpan<byte> contextBytes)

    Creates an authenticated context from a raw byte span.

    contextBytes: ReadOnlySpan<byte>
    The raw bytes comprising the context.

    Retorna: A strongly-typed authenticated context.

  • methodGetHashCode
    public override int GetHashCode()

    Inherits documentation from base type or interface.

  • methodoperator !=
    public static bool operator !=(AuthenticatedContext left, AuthenticatedContext right)

    Determines whether two `AuthenticatedContext` instances are not equal.

    left: AuthenticatedContext
    The first context to compare.
    right: AuthenticatedContext
    The second context to compare.

    Retorna: `true` if instances are not equal; otherwise, `false`.

  • methodoperator ==
    public static bool operator ==(AuthenticatedContext left, AuthenticatedContext right)

    Determines whether two `AuthenticatedContext` instances are equal.

    left: AuthenticatedContext
    The first context to compare.
    right: AuthenticatedContext
    The second context to compare.

    Retorna: `true` if both instances are equal; otherwise, `false`.

  • propertyEmpty
    public static AuthenticatedContext Empty { get; }

    Gets an empty authenticated context.

  • propertyIsEmpty
    public bool IsEmpty { get; }

    Gets a value indicating whether the authenticated context is empty.

  • propertySpan
    public ReadOnlySpan<byte> Span { get; }

    Gets the read-only span representation of the authenticated context bytes.

record

EncryptedData

Ensamblado: EricksonLopez.Security.Abstractions
public readonly record struct EncryptedData(ReadOnlyMemory<byte> Ciphertext, ReadOnlyMemory<byte> Tag, ReadOnlyMemory<byte> Nonce)

Encapsulates the output of an AEAD encryption operation: ciphertext, authentication tag, and initialization nonce.

Miembros (7)

  • constructorEncryptedData
    public EncryptedData(ReadOnlyMemory<byte> Ciphertext, ReadOnlyMemory<byte> Tag, ReadOnlyMemory<byte> Nonce)

    Initializes a new instance of EncryptedData.

    Ciphertext: ReadOnlyMemory<byte>
    The encrypted payload bytes.
    Tag: ReadOnlyMemory<byte>
    The 128-bit (16-byte) AEAD authentication tag.
    Nonce: ReadOnlyMemory<byte>
    The unique 96-bit (12-byte) initialization nonce.
  • propertyCiphertext
    public ReadOnlyMemory<byte> Ciphertext { get; init; }

    The encrypted payload bytes.

  • propertyCiphertextLength
    public int CiphertextLength { get; }

    Gets the length of the ciphertext in bytes.

  • propertyNonce
    public ReadOnlyMemory<byte> Nonce { get; init; }

    The unique 96-bit (12-byte) initialization nonce.

  • propertyNonceLength
    public int NonceLength { get; }

    Gets the length of the nonce in bytes.

  • propertyTag
    public ReadOnlyMemory<byte> Tag { get; init; }

    The 128-bit (16-byte) AEAD authentication tag.

  • propertyTagLength
    public int TagLength { get; }

    Gets the length of the authentication tag in bytes.

interface

IAuthenticatedEncryptionEngine

Ensamblado: EricksonLopez.Security.Abstractions
public interface IAuthenticatedEncryptionEngine

Defines the contract for high-performance, low-allocation Authenticated Encryption with Associated Data (AEAD) engines.

Miembros (7)

  • methodDecrypt
    Result Decrypt(ReadOnlySpan<byte> ciphertext, ReadOnlySpan<byte> key, ReadOnlySpan<byte> nonce, ReadOnlySpan<byte> tag, ReadOnlySpan<byte> associatedData, Span<byte> plaintextDestination, out int bytesWritten)

    Decrypts and authenticates the ciphertext using the specified key, nonce, tag, and associated data into a caller-supplied destination span.

    ciphertext: ReadOnlySpan<byte>
    The encrypted payload span.
    key: ReadOnlySpan<byte>
    The cryptographic key span.
    nonce: ReadOnlySpan<byte>
    The initialization nonce span.
    tag: ReadOnlySpan<byte>
    The authentication tag span.
    associatedData: ReadOnlySpan<byte>
    The associated data span to authenticate.
    plaintextDestination: Span<byte>
    The destination buffer for decrypted bytes.
    bytesWritten: out int
    The number of decrypted bytes written to the destination.

    Retorna: A `Result` indicating success or failure (e.g. tag mismatch, tampered data).

    Security — Payload Size (GAP-01): This method does not enforce an upper bound on `ciphertext` length. When the caller allocates `plaintextDestination` based on untrusted input (e.g. network-received ciphertext), an attacker who controls the payload length can trigger large heap allocations before the authentication tag is verified, potentially causing out-of-memory conditions in constrained environments. Required mitigation: The caller MUST validate `ciphertext.Length` against an application-defined maximum before calling this method. A recommended limit is `256 * 1024 * 1024` bytes (256 MiB) for most workloads. See individual engine implementations (e.g. `AesGcmEncryptionEngine.MaxRecommendedPayloadBytes`) for suggested defaults.

  • methodEncrypt
    Result<EncryptedData> Encrypt(ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> key, ReadOnlySpan<byte> associatedData = default)

    Encrypts the provided plaintext using authenticated encryption with the specified key, generating a fresh random nonce.

    plaintext: ReadOnlySpan<byte>
    The unencrypted data span.
    key: ReadOnlySpan<byte>
    The 256-bit cryptographic key span.
    associatedData: ReadOnlySpan<byte>
    Optional authenticated associated data.

    Retorna: A `Result<T>` containing the `EncryptedData` on success, or a failure error.

  • methodEncrypt
    Result Encrypt(ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> key, Span<byte> nonceDestination, Span<byte> ciphertextDestination, Span<byte> tagDestination, ReadOnlySpan<byte> associatedData = default)

    Encrypts the provided plaintext into caller-provided output spans for zero heap allocations, automatically generating a fresh cryptographically secure random nonce into `nonceDestination` to guarantee nonce-misuse resistance and prevent catastrophic nonce reuse.

    plaintext: ReadOnlySpan<byte>
    The unencrypted data span.
    key: ReadOnlySpan<byte>
    The cryptographic key span.
    nonceDestination: Span<byte>
    The destination span where the freshly generated nonce is written (at least 12 bytes).
    ciphertextDestination: Span<byte>
    The destination span for encrypted bytes (must be at least plaintext.Length).
    tagDestination: Span<byte>
    The destination span for the 16-byte authentication tag.
    associatedData: ReadOnlySpan<byte>
    Optional authenticated associated data.

    Retorna: A `Result` indicating success or a cryptographic failure error.

  • propertyAlgorithm
    AeadAlgorithm Algorithm { get; }

    Gets the AEAD algorithm implemented by this engine.

  • propertyKeySizeBytes
    int KeySizeBytes { get; }

    Gets the required key size in bytes (e.g., 32 bytes for AES-256).

  • propertyNonceSizeBytes
    int NonceSizeBytes { get; }

    Gets the required nonce size in bytes (e.g., 12 bytes).

  • propertyTagSizeBytes
    int TagSizeBytes { get; }

    Gets the required authentication tag size in bytes (e.g., 16 bytes).

interface

IBlindIndexService

Ensamblado: EricksonLopez.Security.Abstractions
public interface IBlindIndexService

Defines a deterministic blind-indexing contract (HMAC-SHA256 with HKDF-derived subkey) for equality searches over encrypted Personally Identifiable Information (PII).

Miembros (1)

  • methodComputeBlindIndex
    string ComputeBlindIndex(string? normalizedPlaintext)

    Computes an uppercase hexadecimal HMAC-SHA256 blind index for the normalized plaintext. Returns `string.Empty` when the input is `null` or whitespace.

    normalizedPlaintext: string?
    The plaintext value to normalize and hash.

    Retorna: A 64-character uppercase hexadecimal HMAC-SHA256 digest, or `string.Empty`.

interface

IDigitalSignatureEngine

Ensamblado: EricksonLopez.Security.Abstractions
public interface IDigitalSignatureEngine

Defines the contract for high-performance digital signature generation and verification.

Miembros (2)

  • methodSign
    Result Sign(ReadOnlySpan<byte> payload, KeyIdentifier keyId, Span<byte> signatureDestination, out int bytesWritten)

    Signs the provided payload using the specified key.

    payload: ReadOnlySpan<byte>
    The data to sign.
    keyId: KeyIdentifier
    The identifier of the private key to use for signing.
    signatureDestination: Span<byte>
    The destination span for the generated signature.
    bytesWritten: out int
    The number of bytes written to the signature destination.

    Retorna: A `Result` indicating success or a cryptographic failure error.

  • methodVerify
    Result Verify(ReadOnlySpan<byte> payload, ReadOnlySpan<byte> signature, KeyIdentifier keyId)

    Verifies the digital signature of the provided payload using the specified key.

    payload: ReadOnlySpan<byte>
    The data that was signed.
    signature: ReadOnlySpan<byte>
    The signature to verify.
    keyId: KeyIdentifier
    The identifier of the public key to use for verification.

    Retorna: A `Result` indicating whether the signature is valid.

interface

IEncryptionKeyProvider

Ensamblado: EricksonLopez.Security.Abstractions
public interface IEncryptionKeyProvider

Defines the contract for providing cryptographic keys for encryption and decryption operations based on purpose and version.

Miembros (2)

  • methodGetActiveEncryptionKeyAsync
    ValueTask<Result<CryptographicKey>> GetActiveEncryptionKeyAsync(KeyPurpose purpose = KeyPurpose.Encryption, CancellationToken cancellationToken = default)

    Gets the current active key for encryption operations.

    purpose: KeyPurpose
    The key purpose (defaults to Encryption).
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the active `CryptographicKey`.

  • methodGetDecryptionKeyAsync
    ValueTask<Result<CryptographicKey>> GetDecryptionKeyAsync(KeyIdentifier keyId, KeyVersion version, CancellationToken cancellationToken = default)

    Gets a specific versioned key for decryption operations.

    keyId: KeyIdentifier
    The key identifier.
    version: KeyVersion
    The key version.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the requested `CryptographicKey`.

interface

ISecurityEnvelopeSerializer

Ensamblado: EricksonLopez.Security.Abstractions
public interface ISecurityEnvelopeSerializer

Defines contracts for serializing and deserializing tamper-resistant binary `SecurityEnvelope` instances.

Miembros (3)

  • methodDeserialize
    Result<SecurityEnvelope> Deserialize(ReadOnlySpan<byte> payload)

    Deserializes a binary payload into a validated `SecurityEnvelope`.

    payload: ReadOnlySpan<byte>
    The binary serialized payload span.

    Retorna: A `Result<T>` containing the reconstructed `SecurityEnvelope` or an error.

  • methodSerialize
    byte[] Serialize(SecurityEnvelope envelope)

    Serializes a `SecurityEnvelope` into a newly allocated binary byte array.

    envelope: SecurityEnvelope
    The envelope to serialize.

    Retorna: A byte array containing the serialized envelope.

  • methodTrySerialize
    bool TrySerialize(SecurityEnvelope envelope, Span<byte> destination, out int bytesWritten)

    Serializes a `SecurityEnvelope` into a caller-supplied destination span for zero allocations.

    envelope: SecurityEnvelope
    The envelope to serialize.
    destination: Span<byte>
    The destination byte span.
    bytesWritten: out int
    The total number of bytes written to the destination.

    Retorna: `true` if the destination buffer was large enough; otherwise, `false`.

record

SecurityEnvelope

Ensamblado: EricksonLopez.Security.Abstractions
public sealed record SecurityEnvelope(byte FormatVersion, AeadAlgorithm Algorithm, KeyIdentifier KeyId, KeyVersion KeyVersion, ReadOnlyMemory<byte> Nonce, ReadOnlyMemory<byte> Tag, ReadOnlyMemory<byte> Ciphertext, ReadOnlyMemory<byte> AssociatedData)

Represents a self-contained, versioned, authenticated cryptographic envelope. Encapsulates format version, algorithm descriptor, key identifier, key version, nonce, auth tag, optional associated data, and ciphertext.

Miembros (13)

  • constructorSecurityEnvelope
    public SecurityEnvelope(byte FormatVersion, AeadAlgorithm Algorithm, KeyIdentifier KeyId, KeyVersion KeyVersion, ReadOnlyMemory<byte> Nonce, ReadOnlyMemory<byte> Tag, ReadOnlyMemory<byte> Ciphertext, ReadOnlyMemory<byte> AssociatedData = default)

    Initializes a new instance of SecurityEnvelope.

    FormatVersion: byte
    The envelope binary format version (e.g., 1).
    Algorithm: AeadAlgorithm
    The applied AEAD algorithm.
    KeyId: KeyIdentifier
    The identifier of the key that encrypted the payload.
    KeyVersion: KeyVersion
    The version of the key that encrypted the payload.
    Nonce: ReadOnlyMemory<byte>
    The cryptographic initialization nonce.
    Tag: ReadOnlyMemory<byte>
    The AEAD authentication tag.
    Ciphertext: ReadOnlyMemory<byte>
    The encrypted payload.
    AssociatedData: ReadOnlyMemory<byte>
    The optional authenticated associated data bound to the envelope.
  • methodToString
    public override string ToString()

    Inherits documentation from base type or interface.

  • propertyAlgorithm
    public AeadAlgorithm Algorithm { get; init; }

    The applied AEAD algorithm.

  • propertyAssociatedData
    public ReadOnlyMemory<byte> AssociatedData { get; init; }

    The optional authenticated associated data bound to the envelope.

  • propertyCiphertext
    public ReadOnlyMemory<byte> Ciphertext { get; init; }

    The encrypted payload.

  • propertyCiphertextLength
    public int CiphertextLength { get; }

    Gets the total payload length in bytes.

  • propertyFormatVersion
    public byte FormatVersion { get; init; }

    The envelope binary format version (e.g., 1).

  • propertyHasAssociatedData
    public bool HasAssociatedData { get; }

    Gets a value indicating whether associated data is present.

  • propertyKeyId
    public KeyIdentifier KeyId { get; init; }

    The identifier of the key that encrypted the payload.

  • propertyKeyVersion
    public KeyVersion KeyVersion { get; init; }

    The version of the key that encrypted the payload.

  • propertyNonce
    public ReadOnlyMemory<byte> Nonce { get; init; }

    The cryptographic initialization nonce.

  • propertyTag
    public ReadOnlyMemory<byte> Tag { get; init; }

    The AEAD authentication tag.

  • fieldCurrentFormatVersion
    public const byte CurrentFormatVersion

    Gets the binary format version number used when serializing new envelopes.

EricksonLopez.Security.Abstractions.Errors#

1
class

SecurityError

Ensamblado: EricksonLopez.Security.Abstractions
public static class SecurityError

Provides standardized, strongly-typed error definitions for all security, cryptographic, key management, token, and secret protection operations across the ecosystem.

Miembros (25)

  • methodAssociatedDataMismatch
    public static Error AssociatedDataMismatch(string? details = null)

    Creates an `Error` representing an authenticated associated data (AAD) context mismatch.

    details: string?
    The optional detailed description of the error.

    Retorna: An `Error` configured with the AAD mismatch validation details.

  • methodAuditFailed
    public static Error AuditFailed(string? details = null)

    Creates an `Error` representing an audit or security event publication failure.

    details: string?
    The optional detailed description of the audit failure.

    Retorna: An `Error` configured with the audit failure details.

  • methodAuthenticationTagMismatch
    public static Error AuthenticationTagMismatch(string? details = null)

    Creates an `Error` representing an AEAD authentication tag mismatch during decryption.

    details: string?
    The optional detailed description of the error.

    Retorna: An `Error` configured with the authentication tag mismatch validation details.

  • methodBufferTooSmall
    public static Error BufferTooSmall(string? details = null)

    Creates an `Error` representing an insufficient destination buffer length.

    details: string?
    The optional detailed description of the error.

    Retorna: An `Error` configured with the buffer too small validation details.

  • methodClientIpNotAllowed
    public static Error ClientIpNotAllowed(string? details = null)

    Creates an `Error` representing a client IP address outside the permitted CIDR allowlist.

    details: string?
    The optional detailed description of the error.

    Retorna: An `Error` configured with the CIDR allowlist violation details.

  • methodClientIpRejected
    public static Error ClientIpRejected(string? details = null)

    Creates an `Error` representing a missing or unparseable client IP address when CIDR enforcement is active.

    details: string?
    The optional detailed description of the error.

    Retorna: An `Error` configured with the client IP rejection details.

  • methodDecryptionFailed
    public static Error DecryptionFailed(string details)

    Creates an `Error` representing a cryptographic decryption failure.

    details: string
    The specific cryptographic fault description.

    Retorna: An `Error` configured with the decryption failure details.

  • methodEncryptionFailed
    public static Error EncryptionFailed(string details)

    Creates an `Error` representing a cryptographic encryption failure.

    details: string
    The specific cryptographic fault description.

    Retorna: An `Error` configured with the encryption failure details.

  • methodInvalidCiphertext
    public static Error InvalidCiphertext(string? details = null)

    Creates an `Error` representing invalid, corrupted, or malformed ciphertext.

    details: string?
    The optional detailed description of the error.

    Retorna: An `Error` configured with the invalid ciphertext failure details.

  • methodInvalidKey
    public static Error InvalidKey(string? details = null)

    Creates an `Error` representing invalid or unsupported cryptographic key material.

    details: string?
    The optional detailed description of the error.

    Retorna: An `Error` configured with the invalid key validation details.

  • methodInvalidNonce
    public static Error InvalidNonce(string? details = null)

    Creates an `Error` representing an invalid or unexpected cryptographic nonce.

    details: string?
    The optional detailed description of the error.

    Retorna: An `Error` configured with the invalid nonce validation details.

  • methodInvalidPassword
    public static Error InvalidPassword(string? details = null)

    Creates an `Error` representing a password verification failure.

    details: string?
    The optional detailed description of the error.

    Retorna: An `Error` configured with the invalid password validation details.

  • methodInvalidToken
    public static Error InvalidToken(string? details = null)

    Creates an `Error` representing an invalid, malformed, or failed signature verification token.

    details: string?
    The optional detailed description of the error.

    Retorna: An `Error` configured with the invalid token validation details.

  • methodKeyExpired
    public static Error KeyExpired(string keyId, string? details = null)

    Creates an `Error` representing an expired cryptographic key.

    keyId: string
    The identifier of the expired cryptographic key.
    details: string?
    The optional detailed description of the error.

    Retorna: An `Error` configured with the key expired failure details.

  • methodKeyNotFound
    public static Error KeyNotFound(string keyId, string? details = null)

    Creates an `Error` representing a missing cryptographic key in the key ring or store.

    keyId: string
    The identifier of the missing cryptographic key.
    details: string?
    The optional detailed description of the error.

    Retorna: An `Error` configured with the key not found details.

  • methodKeyPurposeMismatch
    public static Error KeyPurposeMismatch(string expectedPurpose, string actualPurpose)

    Creates an `Error` representing a mismatch between a key's authorized purpose and requested operation.

    expectedPurpose: string
    The cryptographic purpose required by the attempted operation.
    actualPurpose: string
    The authorized cryptographic purpose configured on the key.

    Retorna: An `Error` configured with the purpose mismatch validation details.

  • methodKeyRevoked
    public static Error KeyRevoked(string keyId, string? details = null)

    Creates an `Error` representing a revoked cryptographic key.

    keyId: string
    The identifier of the revoked cryptographic key.
    details: string?
    The optional detailed description of the error.

    Retorna: An `Error` configured with the key revoked failure details.

  • methodKeyVersionMismatch
    public static Error KeyVersionMismatch(int expectedVersion, int actualVersion)

    Creates an `Error` representing a mismatch between the expected key version and the envelope key version.

    expectedVersion: int
    The expected cryptographic key version.
    actualVersion: int
    The key version embedded in the cryptographic envelope.

    Retorna: An `Error` configured with the key version mismatch details.

  • methodPayloadTooLarge
    public static Error PayloadTooLarge(string? details = null)

    Creates an `Error` representing a payload size exceeding the maximum permitted limit.

    details: string?
    The optional detailed description of the error.

    Retorna: An `Error` configured with the payload size violation details.

  • methodSecretNotFound
    public static Error SecretNotFound(string secretName)

    Creates an `Error` representing a missing secret in the secret store.

    secretName: string
    The name or key of the secret that was not found.

    Retorna: An `Error` configured with the secret not found details.

  • methodSecurityPolicyViolation
    public static Error SecurityPolicyViolation(string policyName, string details)

    Creates an `Error` representing a security policy rule violation.

    policyName: string
    The name of the violated security policy.
    details: string
    The specific rule failure details.

    Retorna: An `Error` configured with the policy violation validation details.

  • methodStoreCapacityExceeded
    public static Error StoreCapacityExceeded(string? details = null)

    Creates an `Error` representing a storage capacity limit breach.

    details: string?
    The optional detailed description of the error.

    Retorna: An `Error` configured with the storage capacity limit details.

  • methodTokenExpired
    public static Error TokenExpired(string? details = null)

    Creates an `Error` representing an expired security token.

    details: string?
    The optional detailed description of the error.

    Retorna: An `Error` configured with the token expired failure details.

  • methodTokenRevoked
    public static Error TokenRevoked(string? details = null)

    Creates an `Error` representing a revoked security token.

    details: string?
    The optional detailed description of the error.

    Retorna: An `Error` configured with the token revoked failure details.

  • methodUnsupportedAlgorithm
    public static Error UnsupportedAlgorithm(string algorithm, string? details = null)

    Creates an `Error` representing an unsupported cryptographic algorithm.

    algorithm: string
    The name or identifier of the unsupported algorithm.
    details: string?
    The optional detailed description of the error.

    Retorna: An `Error` configured with the unsupported algorithm failure details.

EricksonLopez.Security.Abstractions.Events#

8
record

ApiKeyCreatedEvent

Ensamblado: EricksonLopez.Security.Abstractions
public sealed record ApiKeyCreatedEvent(Guid EventId, DateTimeOffset TimestampUtc, ApiKeyId KeyId, string OwnerId, string DisplayPrefix, string? TenantId, string? ActorId) : ISecurityEvent
Implementa: ISecurityEvent

Represents a security event published whenever a new API key is issued.

Miembros (11)

  • constructorApiKeyCreatedEvent
    public ApiKeyCreatedEvent(Guid EventId, DateTimeOffset TimestampUtc, ApiKeyId KeyId, string OwnerId, string DisplayPrefix, string? TenantId = null, string? ActorId = null)

    Initializes a new instance of ApiKeyCreatedEvent.

    EventId: Guid
    Unique identifier for the security event.
    TimestampUtc: DateTimeOffset
    UTC timestamp when the event occurred.
    KeyId: ApiKeyId
    Identifier of the newly created API key.
    OwnerId: string
    Identifier of the user or system that owns the API key.
    DisplayPrefix: string
    Non-sensitive prefix for safe display in user interfaces.
    TenantId: string?
    Optional tenant identifier associated with the key.
    ActorId: string?
    Optional identity of the actor who created the key.
  • methodCreate
    public static ApiKeyCreatedEvent Create(ApiKeyId keyId, string ownerId, string displayPrefix, string? tenantId = null, string? actorId = null)

    Creates a new instance of the `ApiKeyCreatedEvent` record.

    keyId: ApiKeyId
    Identifier of the newly created API key.
    ownerId: string
    Identifier of the user or system that owns the API key.
    displayPrefix: string
    Non-sensitive prefix for safe display in user interfaces.
    tenantId: string?
    Optional tenant identifier associated with the key.
    actorId: string?
    Optional identity of the actor who created the key.

    Retorna: A newly initialized `ApiKeyCreatedEvent` instance.

  • propertyActorId
    public string? ActorId { get; init; }

    Optional identity of the actor who created the key.

  • propertyDisplayPrefix
    public string DisplayPrefix { get; init; }

    Non-sensitive prefix for safe display in user interfaces.

  • propertyEventId
    public Guid EventId { get; init; }

    Unique identifier for the security event.

  • propertyEventType
    public string EventType { get; }

    Gets the standardized semantic name of the event type.

  • propertyKeyId
    public ApiKeyId KeyId { get; init; }

    Identifier of the newly created API key.

  • propertyOwnerId
    public string OwnerId { get; init; }

    Identifier of the user or system that owns the API key.

  • propertySeverity
    public SecurityEventSeverity Severity { get; }

    Gets the severity rating of this security event.

  • propertyTenantId
    public string? TenantId { get; init; }

    Optional tenant identifier associated with the key.

  • propertyTimestampUtc
    public DateTimeOffset TimestampUtc { get; init; }

    UTC timestamp when the event occurred.

record

ApiKeyRevokedEvent

Ensamblado: EricksonLopez.Security.Abstractions
public sealed record ApiKeyRevokedEvent(Guid EventId, DateTimeOffset TimestampUtc, ApiKeyId KeyId, string OwnerId, string Reason, string? TenantId, string? ActorId) : ISecurityEvent
Implementa: ISecurityEvent

Represents a security event published whenever an active API key is revoked.

Miembros (11)

  • constructorApiKeyRevokedEvent
    public ApiKeyRevokedEvent(Guid EventId, DateTimeOffset TimestampUtc, ApiKeyId KeyId, string OwnerId, string Reason, string? TenantId = null, string? ActorId = null)

    Initializes a new instance of ApiKeyRevokedEvent.

    EventId: Guid
    The unique event identifier.
    TimestampUtc: DateTimeOffset
    The UTC timestamp when the event occurred.
    KeyId: ApiKeyId
    The identifier of the revoked API key.
    OwnerId: string
    The identifier of the user or system that owns the API key.
    Reason: string
    The reason explaining why the key was revoked.
    TenantId: string?
    The optional tenant identifier associated with the key.
    ActorId: string?
    The optional identity of the actor who revoked the key.
  • methodCreate
    public static ApiKeyRevokedEvent Create(ApiKeyId keyId, string ownerId, string reason, string? tenantId = null, string? actorId = null)

    Creates a new instance of the `ApiKeyRevokedEvent` record.

    keyId: ApiKeyId
    The identifier of the revoked API key.
    ownerId: string
    The identifier of the user or system that owns the API key.
    reason: string
    The reason explaining why the key was revoked.
    tenantId: string?
    The optional tenant identifier associated with the key.
    actorId: string?
    The optional identity of the actor who revoked the key.

    Retorna: A newly initialized `ApiKeyRevokedEvent` instance.

  • propertyActorId
    public string? ActorId { get; init; }

    The optional identity of the actor who revoked the key.

  • propertyEventId
    public Guid EventId { get; init; }

    The unique event identifier.

  • propertyEventType
    public string EventType { get; }

    Gets the standardized semantic name of the event type.

  • propertyKeyId
    public ApiKeyId KeyId { get; init; }

    The identifier of the revoked API key.

  • propertyOwnerId
    public string OwnerId { get; init; }

    The identifier of the user or system that owns the API key.

  • propertyReason
    public string Reason { get; init; }

    The reason explaining why the key was revoked.

  • propertySeverity
    public SecurityEventSeverity Severity { get; }

    Gets the severity rating of this security event.

  • propertyTenantId
    public string? TenantId { get; init; }

    The optional tenant identifier associated with the key.

  • propertyTimestampUtc
    public DateTimeOffset TimestampUtc { get; init; }

    The UTC timestamp when the event occurred.

interface

ISecurityEvent

Ensamblado: EricksonLopez.Security.Abstractions
public interface ISecurityEvent

Defines a contract for strongly-typed, auditable security events emitted by the security subsystem. Can be consumed directly by application event buses or bridged into `EricksonLopez.Auditing`.

Miembros (6)

  • propertyActorId
    string? ActorId { get; }

    Gets the actor or user ID who initiated the operation.

  • propertyEventId
    Guid EventId { get; }

    Gets the unique identifier of the security event instance.

  • propertyEventType
    string EventType { get; }

    Gets the standardized semantic name of the event type.

  • propertySeverity
    SecurityEventSeverity Severity { get; }

    Gets the severity rating of this security event.

  • propertyTenantId
    string? TenantId { get; }

    Gets the optional tenant or partition identifier.

  • propertyTimestampUtc
    DateTimeOffset TimestampUtc { get; }

    Gets the UTC timestamp when the security event occurred.

record

KeyRevokedEvent

Ensamblado: EricksonLopez.Security.Abstractions
public sealed record KeyRevokedEvent(Guid EventId, DateTimeOffset TimestampUtc, KeyIdentifier KeyId, KeyVersion Version, KeyPurpose Purpose, string Reason, string? TenantId, string? ActorId) : ISecurityEvent
Implementa: ISecurityEvent

Represents a high-severity security event published whenever a cryptographic key is revoked.

Miembros (12)

  • constructorKeyRevokedEvent
    public KeyRevokedEvent(Guid EventId, DateTimeOffset TimestampUtc, KeyIdentifier KeyId, KeyVersion Version, KeyPurpose Purpose, string Reason, string? TenantId = null, string? ActorId = null)

    Initializes a new instance of KeyRevokedEvent.

    EventId: Guid
    Unique identifier for the security event.
    TimestampUtc: DateTimeOffset
    UTC timestamp when the event occurred.
    KeyId: KeyIdentifier
    Identifier of the cryptographic key being revoked.
    Version: KeyVersion
    Version of the key being revoked.
    Purpose: KeyPurpose
    Cryptographic purpose of the revoked key.
    Reason: string
    Explanation for why the key was revoked.
    TenantId: string?
    Optional tenant identifier associated with the key.
    ActorId: string?
    Optional identity of the actor who revoked the key.
  • methodCreate
    public static KeyRevokedEvent Create(KeyIdentifier keyId, KeyVersion version, KeyPurpose purpose, string reason, string? tenantId = null, string? actorId = null)

    Creates a new instance of the `KeyRevokedEvent` record.

    keyId: KeyIdentifier
    Identifier of the cryptographic key being revoked.
    version: KeyVersion
    Version of the key being revoked.
    purpose: KeyPurpose
    Cryptographic purpose of the revoked key.
    reason: string
    Explanation for why the key was revoked.
    tenantId: string?
    Optional tenant identifier associated with the key.
    actorId: string?
    Optional identity of the actor who revoked the key.

    Retorna: A newly initialized `KeyRevokedEvent` instance.

  • propertyActorId
    public string? ActorId { get; init; }

    Optional identity of the actor who revoked the key.

  • propertyEventId
    public Guid EventId { get; init; }

    Unique identifier for the security event.

  • propertyEventType
    public string EventType { get; }

    Gets the standardized semantic name of the event type.

  • propertyKeyId
    public KeyIdentifier KeyId { get; init; }

    Identifier of the cryptographic key being revoked.

  • propertyPurpose
    public KeyPurpose Purpose { get; init; }

    Cryptographic purpose of the revoked key.

  • propertyReason
    public string Reason { get; init; }

    Explanation for why the key was revoked.

  • propertySeverity
    public SecurityEventSeverity Severity { get; }

    Gets the severity rating of this security event.

  • propertyTenantId
    public string? TenantId { get; init; }

    Optional tenant identifier associated with the key.

  • propertyTimestampUtc
    public DateTimeOffset TimestampUtc { get; init; }

    UTC timestamp when the event occurred.

  • propertyVersion
    public KeyVersion Version { get; init; }

    Version of the key being revoked.

record

KeyRotatedEvent

Ensamblado: EricksonLopez.Security.Abstractions
public sealed record KeyRotatedEvent(Guid EventId, DateTimeOffset TimestampUtc, KeyIdentifier KeyId, KeyVersion PreviousVersion, KeyVersion NewVersion, KeyPurpose Purpose, string? TenantId, string? ActorId) : ISecurityEvent
Implementa: ISecurityEvent

Represents a security event published whenever a cryptographic key is rotated.

Miembros (12)

  • constructorKeyRotatedEvent
    public KeyRotatedEvent(Guid EventId, DateTimeOffset TimestampUtc, KeyIdentifier KeyId, KeyVersion PreviousVersion, KeyVersion NewVersion, KeyPurpose Purpose, string? TenantId = null, string? ActorId = null)

    Initializes a new instance of KeyRotatedEvent.

    EventId: Guid
    Unique identifier for the security event.
    TimestampUtc: DateTimeOffset
    UTC timestamp when the event occurred.
    KeyId: KeyIdentifier
    Identifier of the rotated key.
    PreviousVersion: KeyVersion
    Version of the key prior to rotation.
    NewVersion: KeyVersion
    New active version of the key after rotation.
    Purpose: KeyPurpose
    Authorized purpose of the rotated key.
    TenantId: string?
    Optional identifier of the tenant owning the key.
    ActorId: string?
    Optional identifier of the security principal initiating the rotation.
  • methodCreate
    public static KeyRotatedEvent Create(KeyIdentifier keyId, KeyVersion previousVersion, KeyVersion newVersion, KeyPurpose purpose, string? tenantId = null, string? actorId = null)

    Creates a new instance of `KeyRotatedEvent` with automatically generated event ID and current UTC timestamp.

    keyId: KeyIdentifier
    Identifier of the rotated key.
    previousVersion: KeyVersion
    Version of the key prior to rotation.
    newVersion: KeyVersion
    New active version of the key after rotation.
    purpose: KeyPurpose
    Authorized purpose of the rotated key.
    tenantId: string?
    Optional identifier of the tenant owning the key.
    actorId: string?
    Optional identifier of the security principal initiating the rotation.

    Retorna: A newly initialized `KeyRotatedEvent` instance.

  • propertyActorId
    public string? ActorId { get; init; }

    Optional identifier of the security principal initiating the rotation.

  • propertyEventId
    public Guid EventId { get; init; }

    Unique identifier for the security event.

  • propertyEventType
    public string EventType { get; }

    Gets the standardized semantic name of the event type.

  • propertyKeyId
    public KeyIdentifier KeyId { get; init; }

    Identifier of the rotated key.

  • propertyNewVersion
    public KeyVersion NewVersion { get; init; }

    New active version of the key after rotation.

  • propertyPreviousVersion
    public KeyVersion PreviousVersion { get; init; }

    Version of the key prior to rotation.

  • propertyPurpose
    public KeyPurpose Purpose { get; init; }

    Authorized purpose of the rotated key.

  • propertySeverity
    public SecurityEventSeverity Severity { get; }

    Gets the severity rating of this security event.

  • propertyTenantId
    public string? TenantId { get; init; }

    Optional identifier of the tenant owning the key.

  • propertyTimestampUtc
    public DateTimeOffset TimestampUtc { get; init; }

    UTC timestamp when the event occurred.

record

SecretRotatedEvent

Ensamblado: EricksonLopez.Security.Abstractions
public sealed record SecretRotatedEvent(Guid EventId, DateTimeOffset TimestampUtc, string SecretName, string? TenantId, string? ActorId) : ISecurityEvent
Implementa: ISecurityEvent

Represents a security event published whenever a stored secret or credential is rotated.

Miembros (9)

  • constructorSecretRotatedEvent
    public SecretRotatedEvent(Guid EventId, DateTimeOffset TimestampUtc, string SecretName, string? TenantId = null, string? ActorId = null)

    Initializes a new instance of SecretRotatedEvent.

    EventId: Guid
    Unique identifier for the security event.
    TimestampUtc: DateTimeOffset
    UTC timestamp when the event occurred.
    SecretName: string
    Name or identifier of the rotated secret.
    TenantId: string?
    Optional identifier of the tenant owning the secret.
    ActorId: string?
    Optional identifier of the security principal initiating the rotation.
  • methodCreate
    public static SecretRotatedEvent Create(string secretName, string? tenantId = null, string? actorId = null)

    Creates a new instance of `SecretRotatedEvent` with an automatically generated event ID and current UTC timestamp.

    secretName: string
    Name or identifier of the rotated secret.
    tenantId: string?
    Optional identifier of the tenant owning the secret.
    actorId: string?
    Optional identifier of the security principal initiating the rotation.

    Retorna: A newly initialized `SecretRotatedEvent` instance.

  • propertyActorId
    public string? ActorId { get; init; }

    Optional identifier of the security principal initiating the rotation.

  • propertyEventId
    public Guid EventId { get; init; }

    Unique identifier for the security event.

  • propertyEventType
    public string EventType { get; }

    Gets the standardized semantic name of the event type.

  • propertySecretName
    public string SecretName { get; init; }

    Name or identifier of the rotated secret.

  • propertySeverity
    public SecurityEventSeverity Severity { get; }

    Gets the severity rating of this security event.

  • propertyTenantId
    public string? TenantId { get; init; }

    Optional identifier of the tenant owning the secret.

  • propertyTimestampUtc
    public DateTimeOffset TimestampUtc { get; init; }

    UTC timestamp when the event occurred.

enum

SecurityEventSeverity

Ensamblado: EricksonLopez.Security.Abstractions
public enum SecurityEventSeverity

Specifies the severity level of a domain or application security event.

Miembros (4)

  • fieldCritical
    Critical = 4

    Specifies a critical security event (e.g. active tampering detected, authentication tag mismatch attack).

  • fieldHigh
    High = 3

    Specifies a high-impact security event (e.g. key revocation due to suspected compromise, policy violation).

  • fieldInformational
    Informational = 1

    Specifies a routine security lifecycle event (e.g. key rotation, secret creation).

  • fieldWarning
    Warning = 2

    Specifies a notable security condition requiring attention (e.g. rehash required, key approaching expiration).

record

SecurityPolicyViolatedEvent

Ensamblado: EricksonLopez.Security.Abstractions
public sealed record SecurityPolicyViolatedEvent(Guid EventId, DateTimeOffset TimestampUtc, string PolicyName, string ViolationDetails, string? TargetResource, string? TenantId, string? ActorId) : ISecurityEvent
Implementa: ISecurityEvent

Represents a security event emitted whenever a security policy rule is violated.

Miembros (11)

  • constructorSecurityPolicyViolatedEvent
    public SecurityPolicyViolatedEvent(Guid EventId, DateTimeOffset TimestampUtc, string PolicyName, string ViolationDetails, string? TargetResource = null, string? TenantId = null, string? ActorId = null)

    Initializes a new instance of SecurityPolicyViolatedEvent.

    EventId: Guid
    Unique identifier for the security event.
    TimestampUtc: DateTimeOffset
    UTC timestamp when the event occurred.
    PolicyName: string
    Name of the violated security policy.
    ViolationDetails: string
    Detailed diagnostic information describing the policy violation.
    TargetResource: string?
    Optional resource identifier targeted by the violating action.
    TenantId: string?
    Optional identifier of the tenant context.
    ActorId: string?
    Optional identifier of the security principal associated with the violation.
  • methodCreate
    public static SecurityPolicyViolatedEvent Create(string policyName, string violationDetails, string? targetResource = null, string? tenantId = null, string? actorId = null)

    Creates a new instance of `SecurityPolicyViolatedEvent` with an automatically generated event ID and current UTC timestamp.

    policyName: string
    Name of the violated security policy.
    violationDetails: string
    Detailed diagnostic information describing the policy violation.
    targetResource: string?
    Optional resource identifier targeted by the violating action.
    tenantId: string?
    Optional identifier of the tenant context.
    actorId: string?
    Optional identifier of the security principal associated with the violation.

    Retorna: A newly initialized `SecurityPolicyViolatedEvent` instance.

  • propertyActorId
    public string? ActorId { get; init; }

    Optional identifier of the security principal associated with the violation.

  • propertyEventId
    public Guid EventId { get; init; }

    Unique identifier for the security event.

  • propertyEventType
    public string EventType { get; }

    Gets the standardized semantic name of the event type.

  • propertyPolicyName
    public string PolicyName { get; init; }

    Name of the violated security policy.

  • propertySeverity
    public SecurityEventSeverity Severity { get; }

    Gets the severity rating of this security event.

  • propertyTargetResource
    public string? TargetResource { get; init; }

    Optional resource identifier targeted by the violating action.

  • propertyTenantId
    public string? TenantId { get; init; }

    Optional identifier of the tenant context.

  • propertyTimestampUtc
    public DateTimeOffset TimestampUtc { get; init; }

    UTC timestamp when the event occurred.

  • propertyViolationDetails
    public string ViolationDetails { get; init; }

    Detailed diagnostic information describing the policy violation.

EricksonLopez.Security.Abstractions.KeyManagement#

7
interface

IKeyLifecycleManager

Ensamblado: EricksonLopez.Security.Abstractions
public interface IKeyLifecycleManager

Defines contracts for automated cryptographic key lifecycle transitions: generation, rotation, retirement, and revocation.

Miembros (3)

  • methodGenerateAndActivateKeyAsync
    ValueTask<Result<CryptographicKey>> GenerateAndActivateKeyAsync(KeyPurpose purpose, string algorithmId = "", TimeSpan? validityPeriod = null, CancellationToken cancellationToken = default)

    Generates and activates a new cryptographic key for the specified purpose and algorithm.

    purpose: KeyPurpose
    The key purpose.
    algorithmId: string
    The algorithm identifier (e.g. "AES-256-GCM").
    validityPeriod: TimeSpan?
    Optional key expiration validity duration.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the generated and activated `CryptographicKey`.

  • methodRevokeKeyAsync
    ValueTask<Result> RevokeKeyAsync(KeyIdentifier keyId, KeyVersion version, string reason, CancellationToken cancellationToken = default)

    Revokes a specific key immediately, disabling it from all future encryption, signing, and decryption operations.

    keyId: KeyIdentifier
    The key identifier.
    version: KeyVersion
    The key version.
    reason: string
    The revocation reason.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating success or failure.

  • methodRotateKeyAsync
    ValueTask<Result<CryptographicKey>> RotateKeyAsync(KeyPurpose purpose, TimeSpan? validityPeriod = null, CancellationToken cancellationToken = default)

    Rotates the active key for a given purpose: marks the current active key as `KeyStatus.Retired` and generates a new active key with incremented version.

    purpose: KeyPurpose
    The key purpose to rotate.
    validityPeriod: TimeSpan?
    Optional validity period for the new key.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the newly active `CryptographicKey`.

interface

IKeyRevocationNotifier

Ensamblado: EricksonLopez.Security.Abstractions
public interface IKeyRevocationNotifier

Defines a contract for dispatching and receiving real-time key revocation signals across in-process key rings and distributed cluster nodes.

Miembros (2)

  • methodNotifyRevokedAsync
    ValueTask NotifyRevokedAsync(KeyIdentifier keyId, KeyVersion version, KeyPurpose purpose, CancellationToken cancellationToken = default)

    Broadcasts a key revocation notification to all registered listeners.

    keyId: KeyIdentifier
    The identifier of the revoked key.
    version: KeyVersion
    The version of the revoked key.
    purpose: KeyPurpose
    The purpose of the revoked key.
    cancellationToken: CancellationToken
    A token to observe while waiting for the task to complete.

    Retorna: A `ValueTask` representing the asynchronous broadcast operation.

  • methodSubscribe
    IDisposable Subscribe(Action<KeyIdentifier, KeyVersion, KeyPurpose> handler)

    Registers a revocation listener callback invoked when a key revocation signal is received.

    handler: Action<KeyIdentifier, KeyVersion, KeyPurpose>
    The delegate invoked upon key revocation.

    Retorna: An `IDisposable` token that unregisters the callback upon disposal.

interface

IKeyRing

Ensamblado: EricksonLopez.Security.Abstractions
public interface IKeyRing

Defines contracts for querying, resolving, and caching active and legacy cryptographic keys across purpose boundaries and version hierarchies.

Miembros (8)

  • methodGetActiveKey
    Result<CryptographicKey> GetActiveKey(KeyPurpose purpose)

    Synchronously retrieves the current active key for a given purpose.

    purpose: KeyPurpose
    The key purpose.

    Retorna: A `Result<T>` containing the active `CryptographicKey`.

    This synchronous overload blocks the calling thread by calling `GetActiveKeyAsync(...).AsTask().GetAwaiter().GetResult()`. In environments with a `SynchronizationContext` (ASP.NET Framework, WPF, WinForms, Blazor Server) this can deadlock. Prefer `GetActiveKeyAsync` instead.

  • methodGetActiveKeyAsync
    ValueTask<Result<CryptographicKey>> GetActiveKeyAsync(KeyPurpose purpose, CancellationToken cancellationToken = default)

    Asynchronously retrieves the current active key for a given purpose.

    purpose: KeyPurpose
    The key purpose.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the active `CryptographicKey`.

  • methodGetKey
    Result<CryptographicKey> GetKey(KeyIdentifier keyId, KeyVersion version)

    Synchronously retrieves a specific versioned key for decryption or verification.

    keyId: KeyIdentifier
    The key identifier.
    version: KeyVersion
    The key version.

    Retorna: A `Result<T>` containing the requested `CryptographicKey`.

    This synchronous overload blocks the calling thread by calling `GetKeyAsync(...).AsTask().GetAwaiter().GetResult()`. In environments with a `SynchronizationContext` this can deadlock. Prefer `GetKeyAsync` instead.

  • methodGetKeyAsync
    ValueTask<Result<CryptographicKey>> GetKeyAsync(KeyIdentifier keyId, KeyVersion version, CancellationToken cancellationToken = default)

    Asynchronously retrieves a specific versioned key for decryption or verification.

    keyId: KeyIdentifier
    The key identifier.
    version: KeyVersion
    The key version.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the requested `CryptographicKey`.

  • methodInvalidateActiveKey
    void InvalidateActiveKey(KeyPurpose purpose)

    Immediately evicts and scrubs the active key for a given purpose from the local cache.

    purpose: KeyPurpose
    The key purpose whose active cached key should be evicted.
  • methodInvalidateAll
    void InvalidateAll()

    Immediately evicts and scrubs all cached keys and metadata from the local cache.

  • methodInvalidateKey
    void InvalidateKey(KeyIdentifier keyId, KeyVersion version)

    Immediately evicts and scrubs a specific versioned key from the local cache.

    keyId: KeyIdentifier
    The identifier of the key to evict.
    version: KeyVersion
    The version of the key to evict.
  • methodListMetadataAsync
    ValueTask<Result<IReadOnlyList<KeyMetadata>>> ListMetadataAsync(KeyPurpose? purpose = null, CancellationToken cancellationToken = default)

    Asynchronously lists all known key metadata descriptors currently loaded in the key ring.

    purpose: KeyPurpose?
    Optional purpose filter.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a result with a list of key metadata records.

interface

IKeyStore

Ensamblado: EricksonLopez.Security.Abstractions
public interface IKeyStore

Defines contracts for underlying key persistence stores (In-Memory, Database, Vault, KMS, Cloud HSM).

Miembros (4)

  • methodGetKeyAsync
    ValueTask<Result<CryptographicKey>> GetKeyAsync(KeyIdentifier keyId, KeyVersion version, CancellationToken cancellationToken = default)

    Retrieves a cryptographic key by identifier and version.

    keyId: KeyIdentifier
    The key identifier.
    version: KeyVersion
    The key version.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the `CryptographicKey`.

  • methodListMetadataAsync
    ValueTask<Result<IReadOnlyList<KeyMetadata>>> ListMetadataAsync(KeyPurpose? purpose = null, CancellationToken cancellationToken = default)

    Retrieves all key metadata stored in the repository.

    purpose: KeyPurpose?
    Optional purpose filter.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a result with a list of key metadata records.

  • methodSaveKeyAsync
    ValueTask<Result> SaveKeyAsync(CryptographicKey key, CancellationToken cancellationToken = default)

    Persists a new cryptographic key into the key store.

    key: CryptographicKey
    The cryptographic key to save.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating success or failure.

  • methodUpdateStatusAsync
    ValueTask<Result> UpdateStatusAsync(KeyIdentifier keyId, KeyVersion version, KeyStatus newStatus, CancellationToken cancellationToken = default)

    Updates the lifecycle status of a specific key.

    keyId: KeyIdentifier
    The key identifier.
    version: KeyVersion
    The key version.
    newStatus: KeyStatus
    The new lifecycle status.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating the outcome.

interface

IKmsKeyWrappingProvider

Ensamblado: EricksonLopez.Security.Abstractions
public interface IKmsKeyWrappingProvider

Defines a provider for envelope Key Encryption Key (KEK) wrapping and unwrapping operations backed by a Cloud KMS, HSM, or local AEAD root key with optional Authenticated Associated Data (AAD) binding.

Miembros (2)

  • methodUnwrapKeyAsync
    ValueTask<Result<ISecretBuffer>> UnwrapKeyAsync(ReadOnlyMemory<byte> wrappedKey, ReadOnlyMemory<byte> associatedData = default, CancellationToken cancellationToken = default)

    Decrypts (unwraps) previously wrapped key material into a deterministic memory-scrubbing `ISecretBuffer`.

    wrappedKey: ReadOnlyMemory<byte>
    The wrapped key ciphertext bytes produced by `WrapKeyAsync`.
    associatedData: ReadOnlyMemory<byte>
    Optional authenticated associated data that must match the AAD used when wrapping.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A `Result<T>` containing a disposable `ISecretBuffer` whose memory is zeroed on disposal, or a typed security error.

  • methodWrapKeyAsync
    ValueTask<Result<byte[]>> WrapKeyAsync(ReadOnlyMemory<byte> plaintextKey, ReadOnlyMemory<byte> associatedData = default, CancellationToken cancellationToken = default)

    Encrypts (wraps) raw Data Encryption Key (DEK) or PKCS#8 asymmetric private key material under the configured KEK.

    plaintextKey: ReadOnlyMemory<byte>
    The raw key material to wrap. Must not be empty.
    associatedData: ReadOnlyMemory<byte>
    Optional authenticated associated data (for example, key identifier or tenant binding) bound to the wrapped key.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A `Result<T>` containing the opaque wrapped key ciphertext bytes on success, or a typed security error.

interface

IRsaKeyRing

Ensamblado: EricksonLopez.Security.Abstractions
public interface IRsaKeyRing : IDisposable
Implementa: IDisposable

Defines a thread-safe, pure in-memory multi-`kid` RSA asymmetric key ring supporting zero-downtime RS256/PS256 key rotation, signature verification across active and overlap public keys, and JWKS export without persisting unencrypted PEM files to disk.

Miembros (10)

  • methodExportActivePublicKey
    RsaPublicKeyDescriptor ExportActivePublicKey()

    Exports the public key descriptor for the currently active signing key.

    Retorna: The `RsaPublicKeyDescriptor` of the active key.

  • methodExportActiveSigningParameters
    (string KeyId, RSAParameters Parameters) ExportActiveSigningParameters()

    Exports a defensive copy of the currently active signing key's private and public `RSAParameters`. Callers must scrub private parameter arrays after importing them into ephemeral `RSA` or signing wrappers.

    Retorna: A tuple containing the active `kid` and its cloned `RSAParameters`.

  • methodGenerateAndActivateKey
    RsaPublicKeyDescriptor GenerateAndActivateKey(string newKeyId, int keySizeInBits = 2048, TimeSpan? previousKeyOverlapWindow = null)

    Generates a new in-memory RSA key pair of at least 2048 bits, promotes it to active signing key, retains the previous public key in the validation ring for `previousKeyOverlapWindow`, and zeroes the superseded private key parameters in memory.

    newKeyId: string
    The non-empty `kid` for the newly generated key.
    keySizeInBits: int
    The RSA modulus size in bits (minimum 2048, default 2048).
    previousKeyOverlapWindow: TimeSpan?
    Optional overlap validity window for the previously active public key (defaults to 24 hours).

    Retorna: The `RsaPublicKeyDescriptor` of the newly activated key.

  • methodGetValidationKeys
    IReadOnlyList<RsaPublicKeyDescriptor> GetValidationKeys()

    Returns all currently valid (non-expired) RSA public verification keys in the key ring.

    Retorna: An immutable snapshot of active and overlap `RsaPublicKeyDescriptor` entries.

  • methodRegisterPublicValidationKeyPem
    RsaPublicKeyDescriptor RegisterPublicValidationKeyPem(string keyId, ReadOnlySpan<char> publicKeyPem, DateTimeOffset? expiresAtUtc = null)

    Registers an additional public-only RSA key in the validation ring (for example, a historical key during startup overlap).

    keyId: string
    The non-empty `kid` of the public validation key.
    publicKeyPem: ReadOnlySpan<char>
    The PEM-encoded public key (`PUBLIC KEY` or `RSA PUBLIC KEY`).
    expiresAtUtc: DateTimeOffset?
    Optional UTC expiration timestamp for the overlap key.

    Retorna: The registered `RsaPublicKeyDescriptor`.

  • methodRegisterRotatedKey
    RsaPublicKeyDescriptor RegisterRotatedKey(string newKeyId, RSAParameters fullParameters, TimeSpan? previousKeyOverlapWindow = null)

    Promotes externally supplied private `RSAParameters` to the active signing key, retains the previous public key in the validation ring for `previousKeyOverlapWindow`, and zeroes the superseded private key parameters in memory.

    newKeyId: string
    The non-empty `kid` for the rotated key.
    fullParameters: RSAParameters
    The full private and public RSA parameters (minimum 2048-bit modulus).
    previousKeyOverlapWindow: TimeSpan?
    Optional overlap validity window for the previously active public key.

    Retorna: The `RsaPublicKeyDescriptor` of the newly activated key.

  • methodRemoveValidationKey
    bool RemoveValidationKey(string keyId)

    Immediately removes a non-active validation key from the public verification ring (for example, upon emergency key revocation).

    keyId: string
    The `kid` to remove. Cannot be the currently active `ActiveKeyId`.

    Retorna: `true` if the validation key was found and removed; otherwise, `false`.

  • methodSignDataSha256
    byte[] SignDataSha256(ReadOnlySpan<byte> data, RSASignaturePadding? padding = null)

    Computes an RSA-SHA256 digital signature over `data` using the active private key.

    data: ReadOnlySpan<byte>
    The message bytes to sign.
    padding: RSASignaturePadding?
    Optional RSA signature padding (defaults to `RSASignaturePadding.Pkcs1` for RS256).

    Retorna: The raw RSA signature bytes.

  • methodVerifyDataSha256
    bool VerifyDataSha256(ReadOnlySpan<byte> data, ReadOnlySpan<byte> signature, string? keyId = null, RSASignaturePadding? padding = null)

    Verifies an RSA-SHA256 signature against a specific `keyId` (when provided) or across all non-expired validation keys in the ring.

    data: ReadOnlySpan<byte>
    The signed message bytes.
    signature: ReadOnlySpan<byte>
    The RSA signature bytes to verify.
    keyId: string?
    Optional `kid` header hint restricting verification to that specific key.
    padding: RSASignaturePadding?
    Optional RSA signature padding (defaults to `RSASignaturePadding.Pkcs1` for RS256).

    Retorna: `true` if the signature is cryptographically valid for a non-expired validation key; otherwise, `false`.

  • propertyActiveKeyId
    string ActiveKeyId { get; }

    Gets the identifier (`kid`) of the currently active signing key.

record

RsaPublicKeyDescriptor

Ensamblado: EricksonLopez.Security.Abstractions
public sealed record RsaPublicKeyDescriptor(string KeyId, byte[] Modulus, byte[] Exponent, string ModulusBase64Url, string ExponentBase64Url, DateTimeOffset RegisteredAtUtc, DateTimeOffset? ExpiresAtUtc)

Represents an immutable RSA public validation key entry inside an `IRsaKeyRing`, exposing raw big-endian modulus/exponent bytes alongside RFC 7517 JWKS Base64Url components.

Miembros (9)

  • constructorRsaPublicKeyDescriptor
    public RsaPublicKeyDescriptor(string KeyId, byte[] Modulus, byte[] Exponent, string ModulusBase64Url, string ExponentBase64Url, DateTimeOffset RegisteredAtUtc, DateTimeOffset? ExpiresAtUtc = null)

    Initializes a new instance of RsaPublicKeyDescriptor.

    KeyId: string
    The unique key identifier (`kid`).
    Modulus: byte[]
    The unsigned big-endian RSA modulus (`n`) bytes.
    Exponent: byte[]
    The unsigned big-endian RSA public exponent (`e`) bytes.
    ModulusBase64Url: string
    The RFC 7517 Base64Url-encoded RSA modulus (`n`).
    ExponentBase64Url: string
    The RFC 7517 Base64Url-encoded RSA public exponent (`e`).
    RegisteredAtUtc: DateTimeOffset
    The UTC timestamp when this validation key entered the key ring.
    ExpiresAtUtc: DateTimeOffset?
    Optional UTC expiration timestamp after which retired validation keys are no longer accepted.
  • methodToRsaParameters
    public RSAParameters ToRsaParameters()

    Exports defensive copies of `Modulus` and `Exponent` as `RSAParameters`.

    Retorna: An `RSAParameters` structure containing public key parameters only.

  • propertyExpiresAtUtc
    public DateTimeOffset? ExpiresAtUtc { get; init; }

    Optional UTC expiration timestamp after which retired validation keys are no longer accepted.

  • propertyExponent
    public byte[] Exponent { get; init; }

    The unsigned big-endian RSA public exponent (`e`) bytes.

  • propertyExponentBase64Url
    public string ExponentBase64Url { get; init; }

    The RFC 7517 Base64Url-encoded RSA public exponent (`e`).

  • propertyKeyId
    public string KeyId { get; init; }

    The unique key identifier (`kid`).

  • propertyModulus
    public byte[] Modulus { get; init; }

    The unsigned big-endian RSA modulus (`n`) bytes.

  • propertyModulusBase64Url
    public string ModulusBase64Url { get; init; }

    The RFC 7517 Base64Url-encoded RSA modulus (`n`).

  • propertyRegisteredAtUtc
    public DateTimeOffset RegisteredAtUtc { get; init; }

    The UTC timestamp when this validation key entered the key ring.

EricksonLopez.Security.Abstractions.Passwords#

6
interface

IAsyncPasswordHasher

Ensamblado: EricksonLopez.Security.Abstractions
public interface IAsyncPasswordHasher : IPasswordHasher
Implementa: IPasswordHasher

Defines asynchronous password hashing and constant-time verification operations for concurrency-bounded memory-hard KDF engines.

Miembros (2)

  • methodHashPasswordAsync
    ValueTask<string> HashPasswordAsync(string password, CancellationToken ct = default)

    Asynchronously computes a cryptographically salted password hash while respecting bounded concurrency gates.

    password: string
    The plaintext password to hash.
    ct: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A value task containing the encoded password hash string.

  • methodVerifyPasswordAsync
    ValueTask<PasswordVerificationResult> VerifyPasswordAsync(string password, string hashedPassword, CancellationToken ct = default)

    Asynchronously verifies a plaintext password against a stored password hash while respecting bounded concurrency gates.

    password: string
    The candidate plaintext password.
    hashedPassword: string
    The stored password hash string.
    ct: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A value task containing the `PasswordVerificationResult`.

interface

IPasswordHasher

Ensamblado: EricksonLopez.Security.Abstractions
public interface IPasswordHasher

Defines the contract for modern, adaptive password hashing, constant-time verification, and automatic rehash detection.

Miembros (4)

  • methodHashPassword
    string HashPassword(ReadOnlySpan<char> password)

    Computes a cryptographically salted and parameterized password hash for the specified password.

    password: ReadOnlySpan<char>
    The plaintext password character span. Must not exceed 256 characters.

    Retorna: A standardized, self-describing password hash string.

    Exceptions: ArgumentOutOfRangeException: `password` length exceeds 256 characters

  • methodNeedsRehash
    bool NeedsRehash(string hashedPassword)

    Determines whether the given stored password hash requires rehashing due to parameter updates or algorithm evolution.

    hashedPassword: string
    The stored hash string to evaluate

    Retorna: `true` if the hash should be regenerated with current parameters; otherwise, `false`.

  • methodVerifyPassword
    PasswordVerificationResult VerifyPassword(ReadOnlySpan<char> password, string hashedPassword)

    Verifies a plaintext password against a stored hashed password using constant-time evaluation.

    password: ReadOnlySpan<char>
    The candidate password character span to verify
    hashedPassword: string
    The stored hashed password string to evaluate

    Retorna: A `PasswordVerificationResult` indicating success, success with rehash required, or failure.

  • propertyAlgorithm
    PasswordHashAlgorithm Algorithm { get; }

    Gets the primary password hashing algorithm implemented by this instance.

interface

ISimplePasswordHasher

Ensamblado: EricksonLopez.Security.Abstractions
public interface ISimplePasswordHasher

Defines a simplified password hasher contract designed for application-level authentication flows.

Miembros (3)

  • methodHash
    string Hash(string password)

    Computes a cryptographically salted password hash for the specified password.

    password: string
    The plaintext password to hash.

    Retorna: A standardized, self-describing password hash string.

  • methodNeedsRehash
    bool NeedsRehash(string hash)

    Determines whether the given stored password hash requires rehashing due to parameter updates or algorithm evolution.

    hash: string
    The stored hash string.

    Retorna: `true` if the hash should be regenerated with current parameters; otherwise, `false`.

  • methodVerify
    bool Verify(string password, string hash)

    Verifies a plaintext password against a stored hashed password string.

    password: string
    The candidate password to verify.
    hash: string
    The stored hashed password string.

    Retorna: `true` if the password matches the hash; otherwise, `false`.

record

PasswordHash

Ensamblado: EricksonLopez.Security.Abstractions
public readonly record struct PasswordHash : IEquatable<PasswordHash>
Implementa: IEquatable<PasswordHash>

Represents a strongly-typed immutable container for a stored, self-describing password hash string.

Miembros (5)

  • constructorPasswordHash
    public PasswordHash(string value)

    Initializes a new instance of the `PasswordHash` struct.

    value: string
    The hash string.

    Exceptions: ArgumentException: `value` is `null`, empty, or consists only of white-space characters

  • methodToString
    public override string ToString()

    Returns a redacted marker to prevent hash leakage in logs.

    Retorna: A redacted string marker.

  • methodimplicit operator PasswordHash
    public static implicit operator PasswordHash(string value)

    Implicitly converts a string to a `PasswordHash`.

    value: string
    The hash string to convert.

    Retorna: A new `PasswordHash` wrapping `value`.

  • methodimplicit operator string
    public static implicit operator string(PasswordHash hash)

    Implicitly converts a `PasswordHash` to a string.

    hash: PasswordHash
    The `PasswordHash` instance to convert.

    Retorna: The underlying password hash string.

  • propertyValue
    public string Value { get; }

    Gets the raw formatted hash string (e.g. "$pbkdf2-sha512$i=210000$...").

enum

PasswordHashAlgorithm

Ensamblado: EricksonLopez.Security.Abstractions
public enum PasswordHashAlgorithm : byte

Specifies the password hashing algorithm for storing authentication credentials securely.

Miembros (3)

  • fieldArgon2id
    Argon2id = 2

    Specifies the modular crypt format identifier for the `$argon2id$` hash prefix (RFC 9106 MCF).

    Cryptographic Substrate: Hashes carrying this prefix are derived via genuine memory-hard Argon2id (RFC 9106) using `Konscious.Security.Cryptography.Argon2id`. The default parameters enforce 64 MiB memory cost, 3 time-cost iterations, and 4 parallelism lanes, providing robust resistance against GPU and ASIC offline brute-force attacks (see ADR-031).

  • fieldBCrypt
    BCrypt = 3

    Specifies the Openwall or standard BCrypt adaptive password hashing algorithm.

  • fieldPbkdf2HmacSha512
    Pbkdf2HmacSha512 = 1

    Specifies Password-Based Key Derivation Function 2 (PBKDF2) using HMAC-SHA512 per RFC 8018 and OWASP recommendations. Recommended minimum iterations: 600,000+ (or 210,000 for SHA512).

enum

PasswordVerificationResult

Ensamblado: EricksonLopez.Security.Abstractions
public enum PasswordVerificationResult

Specifies the result of a password verification check.

Miembros (3)

  • fieldFailed
    Failed = 3

    Indicates that password verification failed due to incorrect password or corrupted hash.

  • fieldSuccess
    Success = 1

    Indicates that password verification succeeded and the stored hash uses current algorithmic parameters.

  • fieldSuccessRehashNeeded
    SuccessRehashNeeded = 2

    Indicates that password verification succeeded, but the stored hash uses outdated parameters and should be regenerated.

EricksonLopez.Security.Abstractions.Policies#

5
record

ApiKeyPolicy

Ensamblado: EricksonLopez.Security.Abstractions
public sealed record ApiKeyPolicy(int SecretByteLength, TimeSpan? MaxLifetime, bool RequireExpiration) : ISecurityPolicy<ApiKey>
Implementa: ISecurityPolicy<ApiKey>

Defines policy rules governing API key issuance constraints, entropy length, prefix formats, and maximum lifetime.

Miembros (6)

  • constructorApiKeyPolicy
    public ApiKeyPolicy(int SecretByteLength = 32, TimeSpan? MaxLifetime = null, bool RequireExpiration = true)

    Initializes a new instance of ApiKeyPolicy.

    SecretByteLength: int
    Entropy byte length for the secret component (min 24 bytes = 192 bits).
    MaxLifetime: TimeSpan?
    Maximum permitted lifetime for an issued API key (defaults to 365 days).
    RequireExpiration: bool
    Specifies a value indicating whether API keys must have an explicit expiration date.
  • methodValidate
    public Result Validate(ApiKey target)

    Evaluates the policy rules against the target value.

    target: ApiKey
    The target instance to validate.

    Retorna: A `Result` indicating success or containing detailed validation error reasons.

  • propertyMaxLifetime
    public TimeSpan? MaxLifetime { get; init; }

    Maximum permitted lifetime for an issued API key (defaults to 365 days).

  • propertyRequireExpiration
    public bool RequireExpiration { get; init; }

    Specifies a value indicating whether API keys must have an explicit expiration date.

  • propertySecretByteLength
    public int SecretByteLength { get; init; }

    Entropy byte length for the secret component (min 24 bytes = 192 bits).

  • fieldDefault
    public static readonly ApiKeyPolicy Default

    Gets the default API key policy: 32 bytes of secret entropy, 365-day maximum lifetime, and mandatory expiration.

interface

ISecurityPolicy<T>

Ensamblado: EricksonLopez.Security.Abstractions
public interface ISecurityPolicy<T>

Defines a contract for deterministic, immutable, and testable security policies.

Notas:

Type parameters: T: The target entity or value being evaluated.

Miembros (1)

  • methodValidate
    Result Validate(T target)

    Evaluates the policy rules against the target value.

    target: T
    The target instance to validate.

    Retorna: A `Result` indicating success or containing detailed validation error reasons.

record

KeyRotationPolicy

Ensamblado: EricksonLopez.Security.Abstractions
public sealed record KeyRotationPolicy(TimeSpan RotationInterval, TimeSpan RetirementGracePeriod, AeadAlgorithm PreferredAlgorithm) : ISecurityPolicy<KeyMetadata>
Implementa: ISecurityPolicy<KeyMetadata>

Defines policy rules governing automated cryptographic key rotation schedules, grace periods, and algorithms.

Miembros (7)

  • constructorKeyRotationPolicy
    public KeyRotationPolicy(TimeSpan RotationInterval, TimeSpan RetirementGracePeriod, AeadAlgorithm PreferredAlgorithm = AeadAlgorithm.Aes256Gcm)

    Initializes a new instance of KeyRotationPolicy.

    RotationInterval: TimeSpan
    Maximum duration a key remains active before requiring rotation (defaults to 90 days).
    RetirementGracePeriod: TimeSpan
    Duration a retired key remains available for legacy decryption before archival (defaults to 365 days).
    PreferredAlgorithm: AeadAlgorithm
    The preferred AEAD algorithm for newly generated keys.
  • methodValidate
    public Result Validate(KeyMetadata target)

    Evaluates the policy rules against the target value.

    target: KeyMetadata
    The target instance to validate.

    Retorna: A `Result` indicating success or containing detailed validation error reasons.

  • methodValidate
    public Result Validate(KeyMetadata target, DateTimeOffset? nowUtc)

    Validates the key rotation policy against key metadata using a specified reference UTC time.

    target: KeyMetadata
    The key metadata to evaluate.
    nowUtc: DateTimeOffset?
    The reference UTC time (defaults to UtcNow).

    Retorna: A `Result` indicating pass or policy violation.

  • propertyPreferredAlgorithm
    public AeadAlgorithm PreferredAlgorithm { get; init; }

    The preferred AEAD algorithm for newly generated keys.

  • propertyRetirementGracePeriod
    public TimeSpan RetirementGracePeriod { get; init; }

    Duration a retired key remains available for legacy decryption before archival (defaults to 365 days).

  • propertyRotationInterval
    public TimeSpan RotationInterval { get; init; }

    Maximum duration a key remains active before requiring rotation (defaults to 90 days).

  • fieldDefault
    public static readonly KeyRotationPolicy Default

    Gets the default enterprise key rotation policy (90 days rotation, 365 days legacy decryption grace).

record

PasswordPolicy

Ensamblado: EricksonLopez.Security.Abstractions
public sealed record PasswordPolicy(int MinimumLength, int MaximumLength, bool RequireDigit, bool RequireUppercase, bool RequireLowercase, bool RequireNonAlphanumeric, int MaxConsecutiveRepeatedChars) : ISecurityPolicy<string>, ISecurityPolicy<ReadOnlyMemory<char>>
Implementa: ISecurityPolicy<ReadOnlyMemory<char>>, ISecurityPolicy<string>

Defines password strength rules, length constraints, and complexity requirements.

Miembros (13)

  • constructorPasswordPolicy
    public PasswordPolicy(int MinimumLength = 12, int MaximumLength = 128, bool RequireDigit = true, bool RequireUppercase = true, bool RequireLowercase = true, bool RequireNonAlphanumeric = true, int MaxConsecutiveRepeatedChars = 3)

    Initializes a new instance of PasswordPolicy.

    MinimumLength: int
    Minimum required password character length (defaults to 12 per NIST SP 800-63B).
    MaximumLength: int
    Maximum allowed password length (defaults to 128 to prevent computational DoS).
    RequireDigit: bool
    Specifies a value indicating whether at least one numeric character ('0'-'9') is required.
    RequireUppercase: bool
    Specifies a value indicating whether at least one uppercase ASCII letter ('A'-'Z') is required.
    RequireLowercase: bool
    Specifies a value indicating whether at least one lowercase ASCII letter ('a'-'z') is required.
    RequireNonAlphanumeric: bool
    Specifies a value indicating whether at least one non-alphanumeric special character is required.
    MaxConsecutiveRepeatedChars: int
    Maximum allowed consecutive identical characters (0 disables check).
  • methodValidate
    public Result Validate(ReadOnlyMemory<char> target)

    Evaluates the policy rules against the target value.

    target: ReadOnlyMemory<char>
    The target instance to validate.

    Retorna: A `Result` indicating success or containing detailed validation error reasons.

  • methodValidate
    public Result Validate(ReadOnlySpan<char> password)

    Validates password rules against a character span without heap allocations.

    password: ReadOnlySpan<char>
    The password character span.

    Retorna: A `Result` indicating pass or policy violation.

  • methodValidate
    public Result Validate(string target)

    Evaluates the policy rules against the target value.

    target: string
    The target instance to validate.

    Retorna: A `Result` indicating success or containing detailed validation error reasons.

  • propertyMaxConsecutiveRepeatedChars
    public int MaxConsecutiveRepeatedChars { get; init; }

    Maximum allowed consecutive identical characters (0 disables check).

  • propertyMaximumLength
    public int MaximumLength { get; init; }

    Maximum allowed password length (defaults to 128 to prevent computational DoS).

  • propertyMinimumLength
    public int MinimumLength { get; init; }

    Minimum required password character length (defaults to 12 per NIST SP 800-63B).

  • propertyRequireDigit
    public bool RequireDigit { get; init; }

    Specifies a value indicating whether at least one numeric character ('0'-'9') is required.

  • propertyRequireLowercase
    public bool RequireLowercase { get; init; }

    Specifies a value indicating whether at least one lowercase ASCII letter ('a'-'z') is required.

  • propertyRequireNonAlphanumeric
    public bool RequireNonAlphanumeric { get; init; }

    Specifies a value indicating whether at least one non-alphanumeric special character is required.

  • propertyRequireUppercase
    public bool RequireUppercase { get; init; }

    Specifies a value indicating whether at least one uppercase ASCII letter ('A'-'Z') is required.

  • fieldDefault
    public static readonly PasswordPolicy Default

    Gets the enterprise default high-security password policy.

  • fieldNistAligned
    public static readonly PasswordPolicy NistAligned

    Gets a strict NIST SP 800-63B aligned password policy focusing on length (min 15 chars).

record

TokenPolicy

Ensamblado: EricksonLopez.Security.Abstractions
public sealed record TokenPolicy(int MinimumByteLength, TimeSpan? MaxLifetime) : ISecurityPolicy<OpaqueToken>
Implementa: ISecurityPolicy<OpaqueToken>

Defines policy rules governing minimum entropy length and lifetime limits for opaque tokens.

Miembros (5)

  • constructorTokenPolicy
    public TokenPolicy(int MinimumByteLength = 32, TimeSpan? MaxLifetime = null)

    Initializes a new instance of TokenPolicy.

    MinimumByteLength: int
    Minimum entropy byte length (defaults to 32 bytes = 256 bits).
    MaxLifetime: TimeSpan?
    Maximum lifetime for issued tokens (e.g. refresh tokens, reset tokens).
  • methodValidate
    public Result Validate(OpaqueToken target)

    Evaluates the policy rules against the target value.

    target: OpaqueToken
    The target instance to validate.

    Retorna: A `Result` indicating success or containing detailed validation error reasons.

  • propertyMaxLifetime
    public TimeSpan? MaxLifetime { get; init; }

    Maximum lifetime for issued tokens (e.g. refresh tokens, reset tokens).

  • propertyMinimumByteLength
    public int MinimumByteLength { get; init; }

    Minimum entropy byte length (defaults to 32 bytes = 256 bits).

  • fieldDefault
    public static readonly TokenPolicy Default

    Gets the default token policy: 32-byte minimum entropy and 30-day maximum lifetime.

EricksonLopez.Security.Abstractions.Primitives#

21
record

ApiKey

Ensamblado: EricksonLopez.Security.Abstractions
public sealed record ApiKey(ApiKeyId Id, string OwnerId, string Name, string DisplayPrefix, string HashedSecret, DateTimeOffset CreatedAtUtc, DateTimeOffset? ExpiresAtUtc, DateTimeOffset? RevokedAtUtc, IReadOnlySet<string>? Scopes)

Represents an immutable, persisted API key metadata entity without storing the plaintext secret. Stores only the key identifier, display prefix, salted cryptographic hash, and access scopes.

Miembros (17)

  • constructorApiKey
    public ApiKey(ApiKeyId Id, string OwnerId, string Name, string DisplayPrefix, string HashedSecret, DateTimeOffset CreatedAtUtc, DateTimeOffset? ExpiresAtUtc = null, DateTimeOffset? RevokedAtUtc = null, IReadOnlySet<string>? Scopes = null)

    Initializes a new instance of ApiKey.

    Id: ApiKeyId
    Unique API key identifier for indexed lookup.
    OwnerId: string
    Identifier of the owning identity or tenant.
    Name: string
    Human-readable description or client name.
    DisplayPrefix: string
    Safe display prefix (e.g. "ek_live_9f8a...").
    HashedSecret: string
    Secure cryptographic hash of the secret portion.
    CreatedAtUtc: DateTimeOffset
    UTC creation timestamp.
    ExpiresAtUtc: DateTimeOffset?
    Optional UTC expiration timestamp.
    RevokedAtUtc: DateTimeOffset?
    Optional UTC revocation timestamp.
    Scopes: IReadOnlySet<string>?
    Authorized scope strings granted to this API key.
  • methodHasScope
    public bool HasScope(string scope)

    Determines whether the API key is authorized for a specific scope.

    scope: string
    Requested scope name to evaluate.

    Retorna: `true` if authorized; otherwise, `false`.

  • methodIsActive
    public bool IsActive(DateTimeOffset? nowUtc = null)

    Determines whether the API key is currently active, non-revoked, and within both its expiration and rotation grace windows.

    nowUtc: DateTimeOffset?
    Reference UTC timestamp to evaluate against, or `null` to use `DateTimeOffset.UtcNow`.

    Retorna: `true` if valid and active; otherwise, `false`.

  • methodIsClientIpAllowed
    public bool IsClientIpAllowed(IPAddress? clientIp)

    Determines whether the specified client IP address is permitted by `AllowedCidrs`.

    clientIp: IPAddress?
    The client IP address to verify.

    Retorna: `true` if no CIDR restrictions are configured or if `clientIp` falls within at least one allowed CIDR network; otherwise, `false`.

  • propertyAllowedCidrs
    public IReadOnlyList<string>? AllowedCidrs { get; init; }

    Gets the optional list of CIDR network ranges permitted to present this API key. When null or empty, no IP network restriction is enforced.

  • propertyCreatedAtUtc
    public DateTimeOffset CreatedAtUtc { get; init; }

    UTC creation timestamp.

  • propertyDisplayPrefix
    public string DisplayPrefix { get; init; }

    Safe display prefix (e.g. "ek_live_9f8a...").

  • propertyExpiresAtUtc
    public DateTimeOffset? ExpiresAtUtc { get; init; }

    Optional UTC expiration timestamp.

  • propertyGraceUntilUtc
    public DateTimeOffset? GraceUntilUtc { get; init; }

    Gets an optional UTC rotation grace-window deadline. When set after credential rotation, the key ceases to be active once `GraceUntilUtc` elapses even if `ExpiresAtUtc` is later.

  • propertyHashedSecret
    public string HashedSecret { get; init; }

    Secure cryptographic hash of the secret portion.

  • propertyId
    public ApiKeyId Id { get; init; }

    Unique API key identifier for indexed lookup.

  • propertyIsRevoked
    public bool IsRevoked { get; }

    Gets a value indicating whether this API key has been revoked.

  • propertyName
    public string Name { get; init; }

    Human-readable description or client name.

  • propertyOwnerId
    public string OwnerId { get; init; }

    Identifier of the owning identity or tenant.

  • propertyPepperVersion
    public int? PepperVersion { get; init; }

    Gets the optional server HMAC pepper version used when `HashedSecret` was computed.

  • propertyRevokedAtUtc
    public DateTimeOffset? RevokedAtUtc { get; init; }

    Optional UTC revocation timestamp.

  • propertyScopes
    public IReadOnlySet<string>? Scopes { get; init; }

    Authorized scope strings granted to this API key.

record

ApiKeyId

Ensamblado: EricksonLopez.Security.Abstractions
public readonly record struct ApiKeyId : IEquatable<ApiKeyId>, IComparable<ApiKeyId>
Implementa: IComparable<ApiKeyId>, IEquatable<ApiKeyId>

Represents a strongly-typed immutable identifier for an issued API key.

Miembros (11)

  • constructorApiKeyId
    public ApiKeyId(string value)

    Initializes a new instance of the `ApiKeyId` struct.

    value: string
    The unique identifier value.

    Exceptions: ArgumentException: `value` is `null`, empty, or consists only of white-space characters

  • methodCompareTo
    public int CompareTo(ApiKeyId other)

    Inherits documentation from base type or interface.

    other: ApiKeyId
  • methodNew
    public static ApiKeyId New()

    Generates a new random unique `ApiKeyId`.

    Retorna: A new `ApiKeyId`.

  • methodToString
    public override string ToString()

    Inherits documentation from base type or interface.

  • methodimplicit operator ApiKeyId
    public static implicit operator ApiKeyId(string value)

    Implicitly converts a string to an `ApiKeyId`.

    value: string
    The string value to convert.

    Retorna: A new `ApiKeyId` wrapping `value`.

  • methodimplicit operator string
    public static implicit operator string(ApiKeyId id)

    Implicitly converts an `ApiKeyId` to a string.

    id: ApiKeyId
    The `ApiKeyId` instance to convert.

    Retorna: The underlying string identifier.

  • methodoperator <
    public static bool operator <(ApiKeyId left, ApiKeyId right)

    Determines whether one `ApiKeyId` is less than another.

    left: ApiKeyId
    The first instance to compare.
    right: ApiKeyId
    The second instance to compare.

    Retorna: `true` if the left operand is less than the right; otherwise, `false`.

  • methodoperator <=
    public static bool operator <=(ApiKeyId left, ApiKeyId right)

    Determines whether one `ApiKeyId` is less than or equal to another.

    left: ApiKeyId
    The first instance to compare.
    right: ApiKeyId
    The second instance to compare.

    Retorna: `true` if the left operand is less than or equal to the right; otherwise, `false`.

  • methodoperator >
    public static bool operator >(ApiKeyId left, ApiKeyId right)

    Determines whether one `ApiKeyId` is greater than another.

    left: ApiKeyId
    The first instance to compare.
    right: ApiKeyId
    The second instance to compare.

    Retorna: `true` if the left operand is greater than the right; otherwise, `false`.

  • methodoperator >=
    public static bool operator >=(ApiKeyId left, ApiKeyId right)

    Determines whether one `ApiKeyId` is greater than or equal to another.

    left: ApiKeyId
    The first instance to compare.
    right: ApiKeyId
    The second instance to compare.

    Retorna: `true` if the left operand is greater than or equal to the right; otherwise, `false`.

  • propertyValue
    public string Value { get; }

    Gets the raw string identifier of the API key.

enum

AuthenticationAssuranceLevel

Ensamblado: EricksonLopez.Security.Abstractions
public enum AuthenticationAssuranceLevel : byte

Defines the authentication assurance level for a principal session aligned with NIST SP 800-63B.

Miembros (4)

  • fieldAal1
    Aal1 = 1

    NIST AAL1: Single-factor authentication assurance.

  • fieldAal2
    Aal2 = 2

    NIST AAL2: Multi-factor authentication assurance (for example, password plus TOTP or recovery proof).

  • fieldAal3
    Aal3 = 3

    NIST AAL3: Hardware-backed cryptographic multi-factor authentication assurance (for example, FIDO2/WebAuthn hardware authenticator).

  • fieldNone
    None = 0

    Unauthenticated or anonymous context.

class

AuthenticationAssuranceLevelWireFormat

Ensamblado: EricksonLopez.Security.Abstractions
public static class AuthenticationAssuranceLevelWireFormat

Provides canonical wire-claim formatting and parsing helpers for `AuthenticationAssuranceLevel`.

Miembros (2)

  • methodToWireCode
    public static string ToWireCode(this AuthenticationAssuranceLevel level)

    Converts an `AuthenticationAssuranceLevel` value to its canonical lowercase JWT claim string (`"none"`, `"aal1"`, `"aal2"`, or `"aal3"`).

    level: this AuthenticationAssuranceLevel
    The assurance level to format.

    Retorna: The canonical lowercase wire claim value.

    Exceptions: ArgumentOutOfRangeException: `level` is not a defined `AuthenticationAssuranceLevel` value.

  • methodTryParseWireCode
    public static bool TryParseWireCode(string? raw, out AuthenticationAssuranceLevel level)

    Attempts to parse a JWT `aal` claim value into an `AuthenticationAssuranceLevel`.

    raw: string?
    The raw claim value.
    level: out AuthenticationAssuranceLevel
    When this method returns, contains the parsed `AuthenticationAssuranceLevel` if successful.

    Retorna: `true` if `raw` was recognized; otherwise, `false`.

class

CryptographicKey

Ensamblado: EricksonLopez.Security.Abstractions
public sealed class CryptographicKey : IDisposable
Implementa: IDisposable

Encapsulates a cryptographic key consisting of strong metadata and protected in-memory key material. Implements `IDisposable` to wipe key bytes from memory when released.

Miembros (8)

  • constructorCryptographicKey
    public CryptographicKey(KeyMetadata metadata, ISecretBuffer keyMaterial)

    Initializes a new instance of the `CryptographicKey` class.

    metadata: KeyMetadata
    The key metadata.
    keyMaterial: ISecretBuffer
    The memory-managed secret buffer containing the key bytes.

    Exceptions: ArgumentNullException: `metadata` or `keyMaterial` is `null`

  • methodDispose
    public void Dispose()

    Releases the resources used by this instance.

    Scrubs the underlying key material from memory upon disposal.

  • methodGetKeyBytes
    public ReadOnlySpan<byte> GetKeyBytes()

    Returns a readonly span over the raw key bytes for immediate cryptographic execution.

    Retorna: A readonly span containing the raw key material.

    Exceptions: ObjectDisposedException: The key has been disposed

  • methodToString
    public override string ToString()

    Inherits documentation from base type or interface.

  • methodTryCopyKeyBytes
    public bool TryCopyKeyBytes(Span<byte> destination)

    Safely copies the key material to the provided destination span.

    destination: Span<byte>
    The destination buffer.

    Retorna: `true` if successfully copied; otherwise, `false`.

    Exceptions: ObjectDisposedException: The key has been disposed

  • propertyIsDisposed
    public bool IsDisposed { get; }

    Gets a value indicating whether this key has been disposed.

  • propertyKeyLengthInBytes
    public int KeyLengthInBytes { get; }

    Gets the length of the key material in bytes.

  • propertyMetadata
    public KeyMetadata Metadata { get; }

    Gets the immutable metadata associated with this cryptographic key.

record

Fingerprint

Ensamblado: EricksonLopez.Security.Abstractions
public readonly record struct Fingerprint : IEquatable<Fingerprint>, IComparable<Fingerprint>
Implementa: IComparable<Fingerprint>, IEquatable<Fingerprint>

Represents a strongly-typed immutable SHA-256 cryptographic fingerprint for tokens, certificates, and artifacts.

Miembros (10)

  • constructorFingerprint
    public Fingerprint(string hexValue)

    Initializes a new instance of the `Fingerprint` struct from a hex string.

    hexValue: string
    The hex-encoded fingerprint string.

    Exceptions: ArgumentException: `hexValue` is `null`, empty, or consists only of white-space characters

  • methodCompareTo
    public int CompareTo(Fingerprint other)

    Inherits documentation from base type or interface.

    other: Fingerprint
  • methodFromBytes
    public static Fingerprint FromBytes(ReadOnlySpan<byte> data)

    Computes a SHA-256 fingerprint from raw byte span.

    data: ReadOnlySpan<byte>
    The byte span.

    Retorna: A new `Fingerprint`.

  • methodFromUtf8String
    public static Fingerprint FromUtf8String(string input)

    Computes a SHA-256 fingerprint from a UTF-8 string.

    input: string
    The input string.

    Retorna: A new `Fingerprint`.

    Exceptions: ArgumentNullException: `input` is `null`

  • methodToString
    public override string ToString()

    Inherits documentation from base type or interface.

  • methodoperator <
    public static bool operator <(Fingerprint left, Fingerprint right)

    Determines whether one `Fingerprint` is less than another.

    left: Fingerprint
    The first instance to compare.
    right: Fingerprint
    The second instance to compare.

    Retorna: `true` if the left operand is less than the right; otherwise, `false`.

  • methodoperator <=
    public static bool operator <=(Fingerprint left, Fingerprint right)

    Determines whether one `Fingerprint` is less than or equal to another.

    left: Fingerprint
    The first instance to compare.
    right: Fingerprint
    The second instance to compare.

    Retorna: `true` if the left operand is less than or equal to the right; otherwise, `false`.

  • methodoperator >
    public static bool operator >(Fingerprint left, Fingerprint right)

    Determines whether one `Fingerprint` is greater than another.

    left: Fingerprint
    The first instance to compare.
    right: Fingerprint
    The second instance to compare.

    Retorna: `true` if the left operand is greater than the right; otherwise, `false`.

  • methodoperator >=
    public static bool operator >=(Fingerprint left, Fingerprint right)

    Determines whether one `Fingerprint` is greater than or equal to another.

    left: Fingerprint
    The first instance to compare.
    right: Fingerprint
    The second instance to compare.

    Retorna: `true` if the left operand is greater than or equal to the right; otherwise, `false`.

  • propertyHexValue
    public string HexValue { get; }

    Gets the hex-encoded uppercase SHA-256 fingerprint string.

interface

ISecret

Ensamblado: EricksonLopez.Security.Abstractions
public interface ISecret : IDisposable
Implementa: IDisposable

Defines a contract for strongly-typed, memory-safe secrets that prevent accidental leakage and support controlled access to underlying secret data.

Miembros (2)

  • propertyIsDisposed
    bool IsDisposed { get; }

    Gets a value indicating whether this secret container has been disposed and its memory scrubbed.

  • propertyLength
    int Length { get; }

    Gets the length of the secret material in bytes or characters.

interface

ISecretBuffer

Ensamblado: EricksonLopez.Security.Abstractions
public interface ISecretBuffer : ISecret
Implementa: ISecret

Defines a contract for a byte-oriented secret buffer whose underlying memory is scrubbed with `CryptographicOperations.ZeroMemory` upon disposal.

Miembros (1)

  • propertySpan
    ReadOnlySpan<byte> Span { get; }

    Gets a read-only span over the secret buffer for zero-allocation access. Access should be bounded by a `scoped` or `using` block.

    Exceptions: ObjectDisposedException: The buffer has been disposed

interface

ISecret<T>

Ensamblado: EricksonLopez.Security.Abstractions
public interface ISecret<T> : ISecret
Implementa: ISecret

Defines a contract for a strongly-typed generic secret container that provides access to the underlying secret data.

Notas:

Type parameters: T: Type of the underlying secret value.

Miembros (1)

  • propertyValue
    T Value { get; }

    Gets the protected secret value.

    Exceptions: System.ObjectDisposedException: The secret container has been disposed

record

KeyIdentifier

Ensamblado: EricksonLopez.Security.Abstractions
public readonly record struct KeyIdentifier : IEquatable<KeyIdentifier>, IComparable<KeyIdentifier>
Implementa: IComparable<KeyIdentifier>, IEquatable<KeyIdentifier>

Represents a strongly-typed immutable identifier for cryptographic keys, key rings, and secrets. Enforces non-empty invariants and provides URL-safe string representations.

Miembros (13)

  • constructorKeyIdentifier
    public KeyIdentifier(string value)

    Initializes a new instance of the `KeyIdentifier` struct with the specified value.

    value: string
    The key identifier string (cannot be null, empty, or whitespace).

    Exceptions: ArgumentException: `value` is `null`, empty, or consists only of white-space characters

  • methodCompareTo
    public int CompareTo(KeyIdentifier other)

    Inherits documentation from base type or interface.

    other: KeyIdentifier
  • methodNew
    public static KeyIdentifier New()

    Generates a new random, unique `KeyIdentifier` based on a 32-character hexadecimal UUIDv4 representation (Guid "N" format without hyphens).

    Retorna: A new unique `KeyIdentifier`.

  • methodPrefixed
    public static KeyIdentifier Prefixed(string prefix)

    Generates a new `KeyIdentifier` with a given semantic prefix (e.g., "key_sec" producing "key_sec-4fecdac2ba87e980abc123456789abcd").

    prefix: string
    The semantic prefix (cannot be null, empty, or whitespace).

    Retorna: A new unique prefixed `KeyIdentifier`.

    Exceptions: ArgumentException: `prefix` is `null`, empty, or consists only of white-space characters

  • methodToString
    public override string ToString()

    Inherits documentation from base type or interface.

  • methodTryCreate
    public static bool TryCreate(string? value, out KeyIdentifier identifier)

    Attempts to create a `KeyIdentifier` from a raw string.

    value: string?
    The raw string.
    identifier: out KeyIdentifier
    When successful, the created `KeyIdentifier`.

    Retorna: `true` if valid; otherwise, `false`.

  • methodimplicit operator KeyIdentifier
    public static implicit operator KeyIdentifier(string value)

    Implicitly converts a string to a `KeyIdentifier`.

    value: string
    The string value to convert.

    Retorna: A new `KeyIdentifier` wrapping `value`.

  • methodimplicit operator string
    public static implicit operator string(KeyIdentifier identifier)

    Implicitly converts a `KeyIdentifier` to a string.

    identifier: KeyIdentifier
    The `KeyIdentifier` instance to convert.

    Retorna: The underlying string identifier.

  • methodoperator <
    public static bool operator <(KeyIdentifier left, KeyIdentifier right)

    Determines whether one `KeyIdentifier` is less than another.

    left: KeyIdentifier
    The first instance to compare.
    right: KeyIdentifier
    The second instance to compare.

    Retorna: `true` if the left operand is less than the right; otherwise, `false`.

  • methodoperator <=
    public static bool operator <=(KeyIdentifier left, KeyIdentifier right)

    Determines whether one `KeyIdentifier` is less than or equal to another.

    left: KeyIdentifier
    The first instance to compare.
    right: KeyIdentifier
    The second instance to compare.

    Retorna: `true` if the left operand is less than or equal to the right; otherwise, `false`.

  • methodoperator >
    public static bool operator >(KeyIdentifier left, KeyIdentifier right)

    Determines whether one `KeyIdentifier` is greater than another.

    left: KeyIdentifier
    The first instance to compare.
    right: KeyIdentifier
    The second instance to compare.

    Retorna: `true` if the left operand is greater than the right; otherwise, `false`.

  • methodoperator >=
    public static bool operator >=(KeyIdentifier left, KeyIdentifier right)

    Determines whether one `KeyIdentifier` is greater than or equal to another.

    left: KeyIdentifier
    The first instance to compare.
    right: KeyIdentifier
    The second instance to compare.

    Retorna: `true` if the left operand is greater than or equal to the right; otherwise, `false`.

  • propertyValue
    public string Value { get; }

    Gets the underlying string value of the key identifier.

record

KeyMetadata

Ensamblado: EricksonLopez.Security.Abstractions
public sealed record KeyMetadata(KeyIdentifier KeyId, KeyVersion Version, KeyPurpose Purpose, KeyStatus Status, string AlgorithmId, DateTimeOffset CreatedAtUtc, DateTimeOffset? ExpiresAtUtc, DateTimeOffset? RevokedAtUtc)

Represents immutable metadata describing a cryptographic key, its lifecycle state, and cryptographic algorithm bindings.

Miembros (11)

  • constructorKeyMetadata
    public KeyMetadata(KeyIdentifier KeyId, KeyVersion Version, KeyPurpose Purpose, KeyStatus Status, string AlgorithmId, DateTimeOffset CreatedAtUtc, DateTimeOffset? ExpiresAtUtc = null, DateTimeOffset? RevokedAtUtc = null)

    Initializes a new instance of KeyMetadata.

    KeyId: KeyIdentifier
    The unique key identifier.
    Version: KeyVersion
    The monotonic positive key version.
    Purpose: KeyPurpose
    The exclusive authorized purpose of the key.
    Status: KeyStatus
    The lifecycle state of the key.
    AlgorithmId: string
    The cryptographic algorithm standard identifier (e.g., "AES-256-GCM").
    CreatedAtUtc: DateTimeOffset
    The UTC timestamp when the key was created.
    ExpiresAtUtc: DateTimeOffset?
    The optional UTC timestamp when the key expires.
    RevokedAtUtc: DateTimeOffset?
    The optional UTC timestamp when the key was revoked.
  • methodIsUsableForDecryption
    public bool IsUsableForDecryption()

    Determines whether the key is eligible for legacy decryption or verification operations.

    Retorna: `true` if the key is eligible for legacy decryption or verification operations; otherwise, `false`.

  • methodIsUsableForNewOperations
    public bool IsUsableForNewOperations(DateTimeOffset? nowUtc = null)

    Determines whether the key is currently active and within its valid time window.

    nowUtc: DateTimeOffset?
    The reference UTC time (defaults to UtcNow).

    Retorna: `true` if active and not expired; otherwise, `false`.

  • propertyAlgorithmId
    public string AlgorithmId { get; init; }

    The cryptographic algorithm standard identifier (e.g., "AES-256-GCM").

  • propertyCreatedAtUtc
    public DateTimeOffset CreatedAtUtc { get; init; }

    The UTC timestamp when the key was created.

  • propertyExpiresAtUtc
    public DateTimeOffset? ExpiresAtUtc { get; init; }

    The optional UTC timestamp when the key expires.

  • propertyKeyId
    public KeyIdentifier KeyId { get; init; }

    The unique key identifier.

  • propertyPurpose
    public KeyPurpose Purpose { get; init; }

    The exclusive authorized purpose of the key.

  • propertyRevokedAtUtc
    public DateTimeOffset? RevokedAtUtc { get; init; }

    The optional UTC timestamp when the key was revoked.

  • propertyStatus
    public KeyStatus Status { get; init; }

    The lifecycle state of the key.

  • propertyVersion
    public KeyVersion Version { get; init; }

    The monotonic positive key version.

enum

KeyPurpose

Ensamblado: EricksonLopez.Security.Abstractions
public enum KeyPurpose

Specifies the exclusive cryptographic purpose for which a key is authorized. Mitigates key reuse vulnerabilities across incompatible cryptographic operations.

Miembros (6)

  • fieldEncryption
    Encryption = 1

    Specifies that the key is authorized exclusively for authenticated data encryption (e.g., AES-GCM).

  • fieldHashing
    Hashing = 3

    Specifies that the key is authorized exclusively for keyed cryptographic hashing and token derivation.

  • fieldKeyWrapping
    KeyWrapping = 6

    Specifies that the key is authorized exclusively for key-wrapping (encrypting other cryptographic keys).

  • fieldSecretProtection
    SecretProtection = 5

    Specifies that the key is authorized exclusively for encrypting sensitive credentials and secrets at rest.

  • fieldSigning
    Signing = 2

    Specifies that the key is authorized exclusively for digital signatures and HMAC generation.

  • fieldTokenProtection
    TokenProtection = 4

    Specifies that the key is authorized exclusively for protecting, generating, and validating opaque security tokens.

enum

KeyStatus

Ensamblado: EricksonLopez.Security.Abstractions
public enum KeyStatus

Specifies the lifecycle state of a cryptographic key in the key management hierarchy.

Miembros (4)

  • fieldActive
    Active = 1

    Specifies that the key is active and authorized for both encryption/signing and decryption/verification.

  • fieldDestroyed
    Destroyed = 4

    Specifies that the key material has been securely wiped and destroyed.

  • fieldRetired
    Retired = 2

    Specifies that the key has been retired and is authorized only for legacy decryption and verification.

  • fieldRevoked
    Revoked = 3

    Specifies that the key has been revoked and is prohibited for all operations.

record

KeyVersion

Ensamblado: EricksonLopez.Security.Abstractions
public readonly record struct KeyVersion : IEquatable<KeyVersion>, IComparable<KeyVersion>
Implementa: IComparable<KeyVersion>, IEquatable<KeyVersion>

Represents a strongly-typed immutable integer version for cryptographic keys. Enforces positive integer version invariants (>= 1).

Miembros (12)

  • constructorKeyVersion
    public KeyVersion(int value)

    Initializes a new instance of the `KeyVersion` struct with the specified integer version.

    value: int
    The version number (must be >= 1).

    Exceptions: ArgumentOutOfRangeException: `value` is less than 1

  • methodCompareTo
    public int CompareTo(KeyVersion other)

    Inherits documentation from base type or interface.

    other: KeyVersion
  • methodNext
    public KeyVersion Next()

    Produces the next incremental key version.

    Retorna: A new `KeyVersion` with `Value` incremented by 1.

  • methodToString
    public override string ToString()

    Inherits documentation from base type or interface.

  • methodimplicit operator KeyVersion
    public static implicit operator KeyVersion(int value)

    Implicitly converts an integer to a `KeyVersion`.

    value: int
    The version number to convert.

    Retorna: A new `KeyVersion` wrapping `value`.

  • methodimplicit operator int
    public static implicit operator int(KeyVersion version)

    Implicitly converts a `KeyVersion` to an integer.

    version: KeyVersion
    The `KeyVersion` instance to convert.

    Retorna: The underlying integer version value.

  • methodoperator <
    public static bool operator <(KeyVersion left, KeyVersion right)

    Determines whether one `KeyVersion` is less than another.

    left: KeyVersion
    The first instance to compare.
    right: KeyVersion
    The second instance to compare.

    Retorna: `true` if the left operand is less than the right; otherwise, `false`.

  • methodoperator <=
    public static bool operator <=(KeyVersion left, KeyVersion right)

    Determines whether one `KeyVersion` is less than or equal to another.

    left: KeyVersion
    The first instance to compare.
    right: KeyVersion
    The second instance to compare.

    Retorna: `true` if the left operand is less than or equal to the right; otherwise, `false`.

  • methodoperator >
    public static bool operator >(KeyVersion left, KeyVersion right)

    Determines whether one `KeyVersion` is greater than another.

    left: KeyVersion
    The first instance to compare.
    right: KeyVersion
    The second instance to compare.

    Retorna: `true` if the left operand is greater than the right; otherwise, `false`.

  • methodoperator >=
    public static bool operator >=(KeyVersion left, KeyVersion right)

    Determines whether one `KeyVersion` is greater than or equal to another.

    left: KeyVersion
    The first instance to compare.
    right: KeyVersion
    The second instance to compare.

    Retorna: `true` if the left operand is greater than or equal to the right; otherwise, `false`.

  • propertyValue
    public int Value { get; }

    Gets the underlying integer version number.

  • fieldInitial
    public static readonly KeyVersion Initial

    Gets the initial key version (v1).

struct

Nonce

Ensamblado: EricksonLopez.Security.Abstractions
public readonly struct Nonce : IEquatable<Nonce>
Implementa: IEquatable<Nonce>

Represents a strongly-typed immutable container for a cryptographic Initialization Vector (IV) or nonce (number used once). Enforces positive byte length (variable non-empty length supported; standard AES-GCM length is 12 bytes / 96 bits as defined by `AesGcmStandardLength`) and safe copying.

Miembros (13)

  • constructorNonce
    public Nonce(ReadOnlySpan<byte> span)

    Initializes a new instance of the `Nonce` struct by copying from a readonly span.

    span: ReadOnlySpan<byte>
    The nonce byte span.

    Exceptions: ArgumentException: `span` is empty

  • constructorNonce
    public Nonce(byte[] bytes)

    Initializes a new instance of the `Nonce` struct with the specified byte array.

    bytes: byte[]
    The nonce byte array (cannot be empty).

    Exceptions: ArgumentNullException: `bytes` is `null`; ArgumentException: `bytes` is empty

  • methodCopyTo
    public void CopyTo(Span<byte> destination)

    Safely copies the nonce bytes to a destination span.

    destination: Span<byte>
    The destination byte span where the nonce bytes will be copied.
  • methodEquals
    public bool Equals(Nonce other)

    Inherits documentation from base type or interface.

    other: Nonce
  • methodEquals
    public override bool Equals(object? obj)

    Inherits documentation from base type or interface.

    obj: object?
  • methodGetHashCode
    public override int GetHashCode()

    Inherits documentation from base type or interface.

  • methodToString
    public override string ToString()

    Inherits documentation from base type or interface.

  • methodoperator !=
    public static bool operator !=(Nonce left, Nonce right)

    Determines whether two `Nonce` values are not equal.

    left: Nonce
    The first instance to compare.
    right: Nonce
    The second instance to compare.

    Retorna: `true` if the operands are not equal; otherwise, `false`.

  • methodoperator ==
    public static bool operator ==(Nonce left, Nonce right)

    Determines whether two `Nonce` values are equal.

    left: Nonce
    The first instance to compare.
    right: Nonce
    The second instance to compare.

    Retorna: `true` if the operands are equal; otherwise, `false`.

  • propertyLength
    public int Length { get; }

    Gets the length of the nonce in bytes.

  • propertyMemory
    public ReadOnlyMemory<byte> Memory { get; }

    Gets a readonly memory over the nonce bytes.

  • propertySpan
    public ReadOnlySpan<byte> Span { get; }

    Gets a readonly span over the nonce bytes.

  • fieldAesGcmStandardLength
    public const int AesGcmStandardLength

    Standard AES-GCM recommended nonce length (96 bits = 12 bytes).

record

OpaqueToken

Ensamblado: EricksonLopez.Security.Abstractions
public readonly record struct OpaqueToken : IEquatable<OpaqueToken>
Implementa: IEquatable<OpaqueToken>

Represents a strongly-typed immutable container for cryptographically random opaque tokens. Redacts the underlying token in `ToString` to prevent log leakage.

Miembros (7)

  • constructorOpaqueToken
    public OpaqueToken(string value)

    Initializes a new instance of the `OpaqueToken` struct.

    value: string
    The plaintext token string.

    Exceptions: ArgumentException: `value` is `null`, empty, or consists only of white-space characters

  • methodEquals
    public bool Equals(OpaqueToken other)

    Compares two `OpaqueToken` instances for equality.

    other: OpaqueToken
    The other `OpaqueToken` instance to compare with.

    Retorna: `true` if the tokens are equal; otherwise, `false`.

  • methodGetHashCode
    public override int GetHashCode()

    Inherits documentation from base type or interface.

  • methodToString
    public override string ToString()

    Returns a redacted placeholder to prevent leaking the token in logs and traces.

    Retorna: A constant redacted string.

  • propertyIsEmpty
    public bool IsEmpty { get; }

    Gets a value indicating whether this token is empty.

  • propertyLength
    public int Length { get; }

    Gets the length of the token string.

  • propertyValue
    public string Value { get; }

    Gets the raw plaintext token string. Access must be restricted to verification boundaries.

struct

Redacted<T>

Ensamblado: EricksonLopez.Security.Abstractions
public readonly struct Redacted<T> : IEquatable<Redacted<T>>
Implementa: IEquatable<Redacted<T>>

Represents a memory-safe, allocation-conscious wrapper for sensitive data that prevents accidental leakage in logs, exception messages, telemetry traces, and debugger tooltips.

Notas:

Type parameters: T: The type of the sensitive value.

Miembros (10)

  • constructorRedacted
    public Redacted(T? value)

    Initializes a new instance of the `Redacted<T>` struct with the specified sensitive value.

    value: T?
    The sensitive value to protect.
  • methodEquals
    public bool Equals(Redacted<T> other)

    Inherits documentation from base type or interface.

    other: Redacted<T>
  • methodEquals
    public override bool Equals(object? obj)

    Inherits documentation from base type or interface.

    obj: object?
  • methodGetHashCode
    public override int GetHashCode()

    Inherits documentation from base type or interface.

  • methodToString
    public override string ToString()

    Returns the constant redaction marker `[REDACTED]` to prevent accidental leakage when logged or printed.

    Retorna: A redacted string constant.

  • methodimplicit operator Redacted<T>
    public static implicit operator Redacted<T>(T? value)

    Implicitly wraps a sensitive value in a `Redacted<T>` container.

    value: T?
    The sensitive value.

    Retorna: A new `Redacted<T>` container wrapping `value`.

  • methodoperator !=
    public static bool operator !=(Redacted<T> left, Redacted<T> right)

    Determines whether two `Redacted<T>` instances are not equal.

    left: Redacted<T>
    The first instance to compare.
    right: Redacted<T>
    The second instance to compare.

    Retorna: `true` if the operands are not equal; otherwise, `false`.

  • methodoperator ==
    public static bool operator ==(Redacted<T> left, Redacted<T> right)

    Determines whether two `Redacted<T>` instances are equal.

    left: Redacted<T>
    The first instance to compare.
    right: Redacted<T>
    The second instance to compare.

    Retorna: `true` if the operands are equal; otherwise, `false`.

  • propertyHasValue
    public bool HasValue { get; }

    Gets a value indicating whether this instance holds a non-`null` sensitive value.

  • propertyUnsafeValue
    public T? UnsafeValue { get; }

    Gets the underlying sensitive value for explicitly authorized operations.

    Restricts access strictly to cryptographic and validation boundaries.

struct

Salt

Ensamblado: EricksonLopez.Security.Abstractions
public readonly struct Salt : IEquatable<Salt>
Implementa: IEquatable<Salt>

Represents a strongly-typed immutable container for cryptographic salt bytes.

Miembros (13)

  • constructorSalt
    public Salt(ReadOnlySpan<byte> span)

    Initializes a new instance of the `Salt` struct from a readonly span.

    span: ReadOnlySpan<byte>
    The readonly byte span containing the salt bytes.

    Exceptions: ArgumentException: `span` is empty

  • constructorSalt
    public Salt(byte[] bytes)

    Initializes a new instance of the `Salt` struct.

    bytes: byte[]
    The salt byte array.

    Exceptions: ArgumentNullException: `bytes` is `null`; ArgumentException: `bytes` is empty

  • methodCopyTo
    public void CopyTo(Span<byte> destination)

    Safely copies the salt bytes to the destination span.

    destination: Span<byte>
    The destination byte span where the salt bytes will be copied.
  • methodEquals
    public bool Equals(Salt other)

    Inherits documentation from base type or interface.

    other: Salt
  • methodEquals
    public override bool Equals(object? obj)

    Inherits documentation from base type or interface.

    obj: object?
  • methodGetHashCode
    public override int GetHashCode()

    Inherits documentation from base type or interface.

  • methodToString
    public override string ToString()

    Inherits documentation from base type or interface.

  • methodoperator !=
    public static bool operator !=(Salt left, Salt right)

    Determines whether two `Salt` values are not equal.

    left: Salt
    The first instance to compare.
    right: Salt
    The second instance to compare.

    Retorna: `true` if the operands are not equal; otherwise, `false`.

  • methodoperator ==
    public static bool operator ==(Salt left, Salt right)

    Determines whether two `Salt` values are equal.

    left: Salt
    The first instance to compare.
    right: Salt
    The second instance to compare.

    Retorna: `true` if the operands are equal; otherwise, `false`.

  • propertyLength
    public int Length { get; }

    Gets the length of the salt in bytes.

  • propertyMemory
    public ReadOnlyMemory<byte> Memory { get; }

    Gets a readonly memory over the salt bytes.

  • propertySpan
    public ReadOnlySpan<byte> Span { get; }

    Gets a readonly span over the salt bytes.

  • fieldDefaultLength
    public const int DefaultLength

    Standard password hashing recommended salt length (128 bits = 16 bytes).

enum

SecurityPlane

Ensamblado: EricksonLopez.Security.Abstractions
public enum SecurityPlane : byte

Defines the isolated Zero-Trust execution plane of an authenticated principal, separating platform operators (`Control`), tenant-scoped human principals (`Tenant`), and non-human machine-to-machine service principals (`Service`).

Miembros (3)

  • fieldControl
    Control = 0

    Platform-level control plane for system operators without tenant or company data contamination.

  • fieldService
    Service = 2

    Non-human machine-to-machine (M2M) service plane authenticated via scoped service credentials.

  • fieldTenant
    Tenant = 1

    Multi-tenant operational plane for human principals bound to an active tenant and organization unit.

class

SecurityPlaneWireFormat

Ensamblado: EricksonLopez.Security.Abstractions
public static class SecurityPlaneWireFormat

Provides canonical wire-protocol formatting and parsing extensions for `SecurityPlane` claims and GUC contexts.

Miembros (2)

  • methodToWireCode
    public static string ToWireCode(this SecurityPlane plane)

    Converts a `SecurityPlane` value to its canonical uppercase wire code (`"CONTROL"`, `"TENANT"`, or `"M2M"`).

    plane: this SecurityPlane
    The security plane value to format.

    Retorna: The canonical uppercase wire representation.

    Exceptions: ArgumentOutOfRangeException: `plane` is not a defined `SecurityPlane` value.

  • methodTryParseWireCode
    public static bool TryParseWireCode(string? raw, out SecurityPlane plane)

    Attempts to parse a wire representation (`"CONTROL"`, `"TENANT"`, `"M2M"`, or `"SERVICE"`) into a `SecurityPlane`.

    raw: string?
    The raw claim or header string.
    plane: out SecurityPlane
    When this method returns, contains the parsed `SecurityPlane` if successful.

    Retorna: `true` if `raw` matched a canonical security plane code; otherwise, `false`.

record

SecurityStamp

Ensamblado: EricksonLopez.Security.Abstractions
public readonly record struct SecurityStamp : IEquatable<SecurityStamp>
Implementa: IEquatable<SecurityStamp>

Represents a strongly-typed immutable security stamp that invalidates user sessions, refresh tokens, and authorization caches when security-critical state changes.

Miembros (7)

  • constructorSecurityStamp
    public SecurityStamp(string value)

    Initializes a new instance of the `SecurityStamp` struct with the specified value.

    value: string
    The security stamp value.

    Exceptions: ArgumentException: `value` is `null`, empty, or consists only of white-space characters

  • methodNew
    public static SecurityStamp New()

    Generates a new random, unique security stamp.

    Retorna: A new `SecurityStamp` backed by a random UUID-based value.

  • methodToString
    public override string ToString()

    Inherits documentation from base type or interface.

  • methodTryCreate
    public static bool TryCreate(string? value, out SecurityStamp stamp)

    Attempts to parse a string into a `SecurityStamp`.

    value: string?
    The raw string.
    stamp: out SecurityStamp
    When successful, the created `SecurityStamp`.

    Retorna: `true` if valid; otherwise, `false`.

  • methodimplicit operator SecurityStamp
    public static implicit operator SecurityStamp(string value)

    Implicitly converts a string to a `SecurityStamp`.

    value: string
    The string value to convert.

    Retorna: A new `SecurityStamp` wrapping `value`.

  • methodimplicit operator string
    public static implicit operator string(SecurityStamp stamp)

    Implicitly converts a `SecurityStamp` to a string.

    stamp: SecurityStamp
    The `SecurityStamp` instance to convert.

    Retorna: The underlying security stamp string value.

  • propertyValue
    public string Value { get; }

    Gets the raw string representation of the security stamp.

EricksonLopez.Security.Abstractions.Randomness#

2
interface

IConstantTimeComparer

Ensamblado: EricksonLopez.Security.Abstractions
public interface IConstantTimeComparer

Defines contracts for side-channel resistant constant-time comparisons over sensitive buffers.

Miembros (4)

  • methodFixedTimeEquals
    bool FixedTimeEquals(ReadOnlySpan<byte> left, ReadOnlySpan<byte> right)

    Compares two byte spans for equality in execution time independent of data values, preventing side-channel timing attacks.

    left: ReadOnlySpan<byte>
    The left byte span.
    right: ReadOnlySpan<byte>
    The right byte span.

    Retorna: `true` if byte contents are identical and equal length; otherwise, `false`.

  • methodFixedTimeEquals
    bool FixedTimeEquals(ReadOnlySpan<char> left, ReadOnlySpan<char> right)

    Compares two character spans for equality in constant time.

    left: ReadOnlySpan<char>
    The left character span.
    right: ReadOnlySpan<char>
    The right character span.

    Retorna: `true` if characters are identical; otherwise, `false`.

  • methodFixedTimeEqualsSecure
    bool FixedTimeEqualsSecure(ReadOnlySpan<byte> left, ReadOnlySpan<byte> right)

    Compares two byte spans for equality in constant time, eliminating length-leakage side channels by hashing both inputs with a cryptographic digest before constant-time evaluation.

    left: ReadOnlySpan<byte>
    The left byte span.
    right: ReadOnlySpan<byte>
    The right byte span.

    Retorna: `true` if both spans are identical; otherwise, `false`.

  • methodFixedTimeEqualsSecure
    bool FixedTimeEqualsSecure(ReadOnlySpan<char> left, ReadOnlySpan<char> right)

    Compares two character spans for equality in constant time, eliminating length-leakage side channels by hashing both inputs with a cryptographic digest before constant-time evaluation.

    left: ReadOnlySpan<char>
    The left character span.
    right: ReadOnlySpan<char>
    The right character span.

    Retorna: `true` if both spans are identical; otherwise, `false`.

interface

ICryptographicRandomNumberGenerator

Ensamblado: EricksonLopez.Security.Abstractions
public interface ICryptographicRandomNumberGenerator

Defines contracts for cryptographically secure pseudo-random number generators (CSPRNG).

Miembros (3)

  • methodFill
    void Fill(Span<byte> destination)

    Fills the destination byte span with cryptographically strong random bytes.

    destination: Span<byte>
    The destination span.
  • methodGetBytes
    byte[] GetBytes(int count)

    Allocates and fills a byte array with cryptographically strong random bytes.

    count: int
    The number of bytes to generate.

    Retorna: A byte array containing cryptographically strong random bytes.

  • methodGetInt32
    int GetInt32(int fromInclusive, int toExclusive)

    Generates a cryptographically strong random integer within the specified range.

    fromInclusive: int
    The inclusive lower bound.
    toExclusive: int
    The exclusive upper bound.

    Retorna: A cryptographically strong random integer within the specified range.

EricksonLopez.Security.Abstractions.Secrets#

5
interface

ISecretProtector

Ensamblado: EricksonLopez.Security.Abstractions
public interface ISecretProtector

Defines contracts for high-level envelope-based secret protection (encryption and authentication) of sensitive data payloads at rest and in transit.

Miembros (5)

  • methodProtect
    Result<byte[]> Protect(ReadOnlySpan<byte> secret, KeyPurpose purpose = KeyPurpose.SecretProtection, AuthenticatedContext expectedAssociatedData = default)

    Encrypts and authenticates a plaintext secret span into a newly allocated protected payload.

    secret: ReadOnlySpan<byte>
    Plaintext secret byte span.
    purpose: KeyPurpose
    Cryptographic key purpose for encryption (defaults to `KeyPurpose.SecretProtection`).
    expectedAssociatedData: AuthenticatedContext
    Optional authenticated associated data bound to the envelope.

    Retorna: A `Result<T>` containing the serialized protected binary envelope on success.

  • methodProtectAsync
    ValueTask<Result<byte[]>> ProtectAsync(ReadOnlyMemory<byte> secret, KeyPurpose purpose = KeyPurpose.SecretProtection, AuthenticatedContext expectedAssociatedData = default, CancellationToken cancellationToken = default)

    Encrypts and authenticates a secret byte buffer into a protected cryptographic envelope payload.

    secret: ReadOnlyMemory<byte>
    Plaintext secret memory.
    purpose: KeyPurpose
    Cryptographic key purpose (defaults to `KeyPurpose.SecretProtection`).
    expectedAssociatedData: AuthenticatedContext
    Optional authenticated associated data.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the serialized protected binary envelope on success.

  • methodUnprotect
    Result<byte[]> Unprotect(ReadOnlySpan<byte> protectedData, AuthenticatedContext expectedAssociatedData = default)

    Decrypts and authenticates a protected envelope span back into plaintext secret bytes.

    protectedData: ReadOnlySpan<byte>
    Protected binary envelope byte span.
    expectedAssociatedData: AuthenticatedContext
    Optional authenticated associated data to verify against the envelope.

    Retorna: A `Result<T>` containing the decrypted plaintext byte array on success.

  • methodUnprotectAsync
    ValueTask<Result<byte[]>> UnprotectAsync(ReadOnlyMemory<byte> protectedData, AuthenticatedContext expectedAssociatedData = default, CancellationToken cancellationToken = default)

    Decrypts and authenticates a protected cryptographic envelope payload back into plaintext secret bytes.

    protectedData: ReadOnlyMemory<byte>
    Protected binary envelope memory.
    expectedAssociatedData: AuthenticatedContext
    Optional authenticated associated data to verify.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the decrypted plaintext byte array on success.

  • methodUnprotectToSecretBufferAsync
    ValueTask<Result<ISecretBuffer>> UnprotectToSecretBufferAsync(ReadOnlyMemory<byte> protectedData, AuthenticatedContext expectedAssociatedData = default, CancellationToken cancellationToken = default)

    Decrypts and authenticates a protected cryptographic envelope payload into an unmanaged secret buffer whose memory is zeroized upon disposal.

    protectedData: ReadOnlyMemory<byte>
    Protected binary envelope memory.
    expectedAssociatedData: AuthenticatedContext
    Optional authenticated associated data to verify.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the decrypted `ISecretBuffer` on success.

interface

ISecretResolver

Ensamblado: EricksonLopez.Security.Abstractions
public interface ISecretResolver

Defines contracts for resolving secret references (e.g. "env:DATABASE_PASSWORD", "vault:db-creds#secret") across multiple registered provider stores.

Miembros (1)

  • methodResolveAsync
    ValueTask<Result<Redacted<string>>> ResolveAsync(string secretReference, CancellationToken cancellationToken = default)

    Resolves a secret reference string to its unredacted secret value.

    secretReference: string
    The reference URI or key string.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the secret value.

interface

ISecretStore

Ensamblado: EricksonLopez.Security.Abstractions
public interface ISecretStore

Defines contracts for underlying secret storage providers (Environment, DPAPI, Azure Key Vault, AWS Secrets Manager, HashiCorp Vault).

Miembros (2)

  • methodGetSecretAsync
    ValueTask<Result<Redacted<string>>> GetSecretAsync(string secretName, CancellationToken cancellationToken = default)

    Retrieves a secret by name as a memory-safe `Redacted<T>` string container.

    secretName: string
    The unique secret key name.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the secret value.

  • methodSetSecretAsync
    ValueTask<Result> SetSecretAsync(string secretName, string secretValue, CancellationToken cancellationToken = default)

    Sets or updates a secret in the underlying store.

    secretName: string
    The unique secret key name.
    secretValue: string
    The secret value to persist.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating success or failure.

interface

IVersionedSecretProtector

Ensamblado: EricksonLopez.Security.Abstractions
public interface IVersionedSecretProtector

Defines contracts for compact versioned AES-256-GCM secret protection (`v1.<base64url>` and binary envelopes) with external `AuthenticatedContext` / span / string AAD binding and HKDF key-version subkey isolation.

Notas:

Implementations omit AAD from persisted envelopes so callers must reconstruct the exact owning context (`tenantId`, `companyId`, `userId`, `purpose`) at decryption time, defeating database row-swap and cross-tenant confused-deputy attacks.

Miembros (29)

  • methodProtect
    Result<VersionedSecretEnvelope> Protect(ReadOnlySpan<byte> plaintext, string purpose, AuthenticatedContext associatedData)

    Encrypts and authenticates a plaintext byte span into a versioned `v1.<base64url>` envelope bound to external AAD.

    plaintext: ReadOnlySpan<byte>
    The plaintext secret bytes to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: AuthenticatedContext
    The external authenticated context (AAD) bound to the authentication tag.

    Retorna: A `Result<T>` containing the `VersionedSecretEnvelope` on success.

  • methodProtect
    Result<VersionedSecretEnvelope> Protect(ReadOnlySpan<byte> plaintext, string purpose, ReadOnlySpan<byte> associatedData)

    Encrypts and authenticates a plaintext byte span into a versioned `v1.<base64url>` envelope bound to raw AAD bytes.

    plaintext: ReadOnlySpan<byte>
    The plaintext secret bytes to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: ReadOnlySpan<byte>
    The raw associated data bytes bound to the authentication tag.

    Retorna: A `Result<T>` containing the `VersionedSecretEnvelope` on success.

  • methodProtect
    Result<VersionedSecretEnvelope> Protect(ReadOnlySpan<byte> plaintext, string purpose, string? associatedDataContext)

    Encrypts and authenticates a plaintext byte span into a versioned `v1.<base64url>` envelope bound to a UTF-8 AAD context string.

    plaintext: ReadOnlySpan<byte>
    The plaintext secret bytes to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedDataContext: string?
    The UTF-8 associated data context string bound to the authentication tag.

    Retorna: A `Result<T>` containing the `VersionedSecretEnvelope` on success.

  • methodProtectString
    Result<VersionedSecretEnvelope> ProtectString(string plaintext, string purpose, AuthenticatedContext associatedData)

    Encrypts and authenticates a UTF-8 plaintext secret string into a versioned `v1.<base64url>` envelope, scrubbing intermediate UTF-8 plaintext bytes from memory before returning.

    plaintext: string
    The non-empty plaintext string to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: AuthenticatedContext
    The external authenticated context (AAD) bound to the authentication tag.

    Retorna: A `Result<T>` containing the `VersionedSecretEnvelope` on success.

  • methodProtectString
    Result<VersionedSecretEnvelope> ProtectString(string plaintext, string purpose, ReadOnlySpan<byte> associatedData)

    Encrypts and authenticates a UTF-8 plaintext secret string into a versioned `v1.<base64url>` envelope bound to raw AAD bytes.

    plaintext: string
    The non-empty plaintext string to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: ReadOnlySpan<byte>
    The raw associated data bytes bound to the authentication tag.

    Retorna: A `Result<T>` containing the `VersionedSecretEnvelope` on success.

  • methodProtectString
    Result<VersionedSecretEnvelope> ProtectString(string plaintext, string purpose, string? associatedDataContext)

    Encrypts and authenticates a UTF-8 plaintext secret string into a versioned `v1.<base64url>` envelope bound to a UTF-8 AAD context string.

    plaintext: string
    The non-empty plaintext string to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedDataContext: string?
    The UTF-8 associated data context string bound to the authentication tag.

    Retorna: A `Result<T>` containing the `VersionedSecretEnvelope` on success.

  • methodProtectStringToBytes
    Result<byte[]> ProtectStringToBytes(string plaintext, string purpose, AuthenticatedContext associatedData)

    Encrypts and authenticates a UTF-8 plaintext string into a compact binary versioned AEAD payload, scrubbing intermediate plaintext bytes.

    plaintext: string
    The non-empty plaintext string to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: AuthenticatedContext
    The external authenticated context (AAD) bound to the authentication tag.

    Retorna: A `Result<T>` containing the binary versioned AEAD payload on success.

  • methodProtectStringToBytes
    Result<byte[]> ProtectStringToBytes(string plaintext, string purpose, ReadOnlySpan<byte> associatedData)

    Encrypts and authenticates a UTF-8 plaintext string into a compact binary versioned AEAD payload bound to raw AAD bytes.

    plaintext: string
    The non-empty plaintext string to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: ReadOnlySpan<byte>
    The raw associated data bytes bound to the authentication tag.

    Retorna: A `Result<T>` containing the binary versioned AEAD payload on success.

  • methodProtectStringToBytes
    Result<byte[]> ProtectStringToBytes(string plaintext, string purpose, string? associatedDataContext)

    Encrypts and authenticates a UTF-8 plaintext string into a compact binary versioned AEAD payload bound to a UTF-8 AAD context string.

    plaintext: string
    The non-empty plaintext string to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedDataContext: string?
    The UTF-8 associated data context string bound to the authentication tag.

    Retorna: A `Result<T>` containing the binary versioned AEAD payload on success.

  • methodProtectToBytes
    Result<byte[]> ProtectToBytes(ReadOnlySpan<byte> plaintext, string purpose, AuthenticatedContext associatedData)

    Encrypts and authenticates a plaintext byte span into a compact binary versioned AEAD payload.

    plaintext: ReadOnlySpan<byte>
    The plaintext secret bytes to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: AuthenticatedContext
    The external authenticated context (AAD) bound to the authentication tag.

    Retorna: A `Result<T>` containing the binary versioned AEAD payload on success.

  • methodProtectToBytes
    Result<byte[]> ProtectToBytes(ReadOnlySpan<byte> plaintext, string purpose, ReadOnlySpan<byte> associatedData)

    Encrypts and authenticates a plaintext byte span into a compact binary versioned AEAD payload bound to raw AAD bytes.

    plaintext: ReadOnlySpan<byte>
    The plaintext secret bytes to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: ReadOnlySpan<byte>
    The raw associated data bytes bound to the authentication tag.

    Retorna: A `Result<T>` containing the binary versioned AEAD payload on success.

  • methodProtectToBytes
    Result<byte[]> ProtectToBytes(ReadOnlySpan<byte> plaintext, string purpose, string? associatedDataContext)

    Encrypts and authenticates a plaintext byte span into a compact binary versioned AEAD payload bound to a UTF-8 AAD context string.

    plaintext: ReadOnlySpan<byte>
    The plaintext secret bytes to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedDataContext: string?
    The UTF-8 associated data context string bound to the authentication tag.

    Retorna: A `Result<T>` containing the binary versioned AEAD payload on success.

  • methodUnprotect
    Result<byte[]> Unprotect(string ciphertextEnvelope, string purpose, AuthenticatedContext associatedData, int expectedKeyVersion = 0)

    Decrypts and authenticates a `v1.<base64url>` envelope using the reconstructed external AAD and optional expected key version.

    ciphertextEnvelope: string
    The persisted `v1.<base64url>` envelope string.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: AuthenticatedContext
    The external authenticated context (AAD) to verify.
    expectedKeyVersion: int
    Optional expected key version (`> 0` enforces exact header match; `<= 0` accepts any loaded version in the key ring).

    Retorna: A `Result<T>` containing the decrypted plaintext byte array on success.

  • methodUnprotect
    Result<byte[]> Unprotect(string ciphertextEnvelope, string purpose, ReadOnlySpan<byte> associatedData, int expectedKeyVersion = 0)

    Decrypts and authenticates a `v1.<base64url>` envelope using raw external AAD bytes and optional expected key version.

    ciphertextEnvelope: string
    The persisted `v1.<base64url>` envelope string.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: ReadOnlySpan<byte>
    The raw associated data bytes to verify.
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted plaintext byte array on success.

  • methodUnprotect
    Result<byte[]> Unprotect(string ciphertextEnvelope, string purpose, string? associatedDataContext, int expectedKeyVersion = 0)

    Decrypts and authenticates a `v1.<base64url>` envelope using a UTF-8 AAD context string and optional expected key version.

    ciphertextEnvelope: string
    The persisted `v1.<base64url>` envelope string.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedDataContext: string?
    The UTF-8 associated data context string to verify.
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted plaintext byte array on success.

  • methodUnprotectFromBytes
    Result<byte[]> UnprotectFromBytes(ReadOnlySpan<byte> ciphertextPayload, string purpose, AuthenticatedContext associatedData, int expectedKeyVersion = 0)

    Decrypts and authenticates a compact binary versioned AEAD payload using external `AuthenticatedContext` AAD.

    ciphertextPayload: ReadOnlySpan<byte>
    The binary versioned AEAD payload produced by `ProtectToBytes(ReadOnlySpan<byte>, string, AuthenticatedContext)`.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: AuthenticatedContext
    The external authenticated context (AAD) to verify.
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted plaintext byte array on success.

  • methodUnprotectFromBytes
    Result<byte[]> UnprotectFromBytes(ReadOnlySpan<byte> ciphertextPayload, string purpose, ReadOnlySpan<byte> associatedData, int expectedKeyVersion = 0)

    Decrypts and authenticates a compact binary versioned AEAD payload using raw AAD bytes.

    ciphertextPayload: ReadOnlySpan<byte>
    The binary versioned AEAD payload.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: ReadOnlySpan<byte>
    The raw associated data bytes to verify.
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted plaintext byte array on success.

  • methodUnprotectFromBytes
    Result<byte[]> UnprotectFromBytes(ReadOnlySpan<byte> ciphertextPayload, string purpose, string? associatedDataContext, int expectedKeyVersion = 0)

    Decrypts and authenticates a compact binary versioned AEAD payload using a UTF-8 AAD context string.

    ciphertextPayload: ReadOnlySpan<byte>
    The binary versioned AEAD payload.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedDataContext: string?
    The UTF-8 associated data context string to verify.
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted plaintext byte array on success.

  • methodUnprotectString
    Result<string> UnprotectString(string ciphertextEnvelope, string purpose, AuthenticatedContext associatedData, int expectedKeyVersion = 0)

    Decrypts and authenticates a `v1.<base64url>` envelope into a UTF-8 string, scrubbing intermediate decrypted byte buffers via `ZeroMemory` before returning.

    ciphertextEnvelope: string
    The persisted `v1.<base64url>` envelope string.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: AuthenticatedContext
    The external authenticated context (AAD) to verify.
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted UTF-8 string on success.

  • methodUnprotectString
    Result<string> UnprotectString(string ciphertextEnvelope, string purpose, ReadOnlySpan<byte> associatedData, int expectedKeyVersion = 0)

    Decrypts and authenticates a `v1.<base64url>` envelope into a UTF-8 string using raw AAD bytes.

    ciphertextEnvelope: string
    The persisted `v1.<base64url>` envelope string.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: ReadOnlySpan<byte>
    The raw associated data bytes to verify.
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted UTF-8 string on success.

  • methodUnprotectString
    Result<string> UnprotectString(string ciphertextEnvelope, string purpose, string? associatedDataContext, int expectedKeyVersion = 0)

    Decrypts and authenticates a `v1.<base64url>` envelope into a UTF-8 string using a UTF-8 AAD context string.

    ciphertextEnvelope: string
    The persisted `v1.<base64url>` envelope string.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedDataContext: string?
    The UTF-8 associated data context string to verify.
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted UTF-8 string on success.

  • methodUnprotectStringFromBytes
    Result<string> UnprotectStringFromBytes(ReadOnlySpan<byte> ciphertextPayload, string purpose, AuthenticatedContext associatedData, int expectedKeyVersion = 0)

    Decrypts and authenticates a compact binary versioned AEAD payload into a UTF-8 string, scrubbing intermediate buffers.

    ciphertextPayload: ReadOnlySpan<byte>
    The binary versioned AEAD payload.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: AuthenticatedContext
    The external authenticated context (AAD) to verify.
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted UTF-8 string on success.

  • methodUnprotectStringFromBytes
    Result<string> UnprotectStringFromBytes(ReadOnlySpan<byte> ciphertextPayload, string purpose, ReadOnlySpan<byte> associatedData, int expectedKeyVersion = 0)

    Decrypts and authenticates a compact binary versioned AEAD payload into a UTF-8 string using raw AAD bytes.

    ciphertextPayload: ReadOnlySpan<byte>
    The binary versioned AEAD payload.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: ReadOnlySpan<byte>
    The raw associated data bytes to verify.
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted UTF-8 string on success.

  • methodUnprotectStringFromBytes
    Result<string> UnprotectStringFromBytes(ReadOnlySpan<byte> ciphertextPayload, string purpose, string? associatedDataContext, int expectedKeyVersion = 0)

    Decrypts and authenticates a compact binary versioned AEAD payload into a UTF-8 string using a UTF-8 AAD context string.

    ciphertextPayload: ReadOnlySpan<byte>
    The binary versioned AEAD payload.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedDataContext: string?
    The UTF-8 associated data context string to verify.
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted UTF-8 string on success.

  • methodUnprotectToSecretBuffer
    Result<ISecretBuffer> UnprotectToSecretBuffer(string ciphertextEnvelope, string purpose, AuthenticatedContext associatedData, int expectedKeyVersion = 0)

    Decrypts and authenticates a `v1.<base64url>` envelope directly into a zeroizable `ISecretBuffer`.

    ciphertextEnvelope: string
    The persisted `v1.<base64url>` envelope string.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: AuthenticatedContext
    The external authenticated context (AAD) to verify.
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted `ISecretBuffer` on success.

  • methodUnprotectToSecretBuffer
    Result<ISecretBuffer> UnprotectToSecretBuffer(string ciphertextEnvelope, string purpose, ReadOnlySpan<byte> associatedData, int expectedKeyVersion = 0)

    Decrypts and authenticates a `v1.<base64url>` envelope directly into a zeroizable `ISecretBuffer` using raw AAD bytes.

    ciphertextEnvelope: string
    The persisted `v1.<base64url>` envelope string.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: ReadOnlySpan<byte>
    The raw associated data bytes to verify.
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted `ISecretBuffer` on success.

  • methodUnprotectToSecretBuffer
    Result<ISecretBuffer> UnprotectToSecretBuffer(string ciphertextEnvelope, string purpose, string? associatedDataContext, int expectedKeyVersion = 0)

    Decrypts and authenticates a `v1.<base64url>` envelope directly into a zeroizable `ISecretBuffer` using a UTF-8 AAD context string.

    ciphertextEnvelope: string
    The persisted `v1.<base64url>` envelope string.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedDataContext: string?
    The UTF-8 associated data context string to verify.
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted `ISecretBuffer` on success.

  • propertyActiveKeyVersion
    int ActiveKeyVersion { get; }

    Gets the currently active master key version used for new encryption operations.

  • propertyRequireAssociatedData
    bool RequireAssociatedData { get; }

    Gets a value indicating whether non-empty associated data (AAD) is mandatory for all protect and unprotect operations.

record

VersionedSecretEnvelope

Ensamblado: EricksonLopez.Security.Abstractions
public readonly record struct VersionedSecretEnvelope(string Ciphertext, int KeyVersion)

Represents a compact, versioned AEAD ciphertext text envelope (`v1.<base64url>`) paired with the master key version used during protection.

Miembros (3)

  • constructorVersionedSecretEnvelope
    public VersionedSecretEnvelope(string Ciphertext, int KeyVersion)

    Initializes a new instance of VersionedSecretEnvelope.

    Ciphertext: string
    The URL-safe versioned ciphertext envelope string (`v1.<base64url>`).
    KeyVersion: int
    The positive master key version used to derive the encryption subkey.
  • propertyCiphertext
    public string Ciphertext { get; init; }

    The URL-safe versioned ciphertext envelope string (`v1.<base64url>`).

  • propertyKeyVersion
    public int KeyVersion { get; init; }

    The positive master key version used to derive the encryption subkey.

EricksonLopez.Security.Abstractions.Tokens#

13
record

ApiKeyIssuanceResult

Ensamblado: EricksonLopez.Security.Abstractions
public sealed record ApiKeyIssuanceResult(ApiKey Key, string PlaintextApiKey)

Represents the result of issuing a new API key.

Notas:

Contains the persisted `ApiKey` descriptor (with hashed secret) and the single-use plaintext secret string that must be returned once to the caller.

Miembros (3)

  • constructorApiKeyIssuanceResult
    public ApiKeyIssuanceResult(ApiKey Key, string PlaintextApiKey)

    Initializes a new instance of ApiKeyIssuanceResult.

    Key: ApiKey
    The persisted API key entity.
    PlaintextApiKey: string
    The full plaintext API key string (e.g., "ek_live_9f8a...").

    Contains the persisted `ApiKey` descriptor (with hashed secret) and the single-use plaintext secret string that must be returned once to the caller.

  • propertyKey
    public ApiKey Key { get; init; }

    The persisted API key entity.

  • propertyPlaintextApiKey
    public string PlaintextApiKey { get; init; }

    The full plaintext API key string (e.g., "ek_live_9f8a...").

record

GeneratedBackupCode

Ensamblado: EricksonLopez.Security.Abstractions
public readonly record struct GeneratedBackupCode(string PlaintextCode, string HmacHexDigest, int PepperVersion)

Represents a newly issued single-use emergency backup code formatted as `XXXX-XXXX-XXXX`, paired with its normalized domain-separated HMAC-SHA256 digest and active pepper version.

Miembros (4)

  • constructorGeneratedBackupCode
    public GeneratedBackupCode(string PlaintextCode, string HmacHexDigest, int PepperVersion)

    Initializes a new instance of GeneratedBackupCode.

    PlaintextCode: string
    The plaintext backup code formatted for one-time user display (for example, `ABCD-2345-EFGH`).
    HmacHexDigest: string
    The 64-character lowercase hexadecimal HMAC-SHA256 digest over the normalized code.
    PepperVersion: int
    The server HMAC pepper version used to compute `HmacHexDigest`.
  • propertyHmacHexDigest
    public string HmacHexDigest { get; init; }

    The 64-character lowercase hexadecimal HMAC-SHA256 digest over the normalized code.

  • propertyPepperVersion
    public int PepperVersion { get; init; }

    The server HMAC pepper version used to compute `HmacHexDigest`.

  • propertyPlaintextCode
    public string PlaintextCode { get; init; }

    The plaintext backup code formatted for one-time user display (for example, `ABCD-2345-EFGH`).

interface

IApiKeyGenerator

Ensamblado: EricksonLopez.Security.Abstractions
public interface IApiKeyGenerator

Defines a contract for issuing cryptographically secure API keys with display prefixes and hashed secrets.

Miembros (1)

  • methodGenerateApiKey
    ApiKeyIssuanceResult GenerateApiKey(string ownerId, string name, string prefix = "", TimeSpan? lifetime = null, IReadOnlySet<string>? scopes = null)

    Generates a new structured API key with the specified metadata and constraints.

    ownerId: string
    The identifier of the owning entity or tenant
    name: string
    The descriptive name for the API key
    prefix: string
    The display prefix to prepend to the key
    lifetime: TimeSpan?
    The optional lifetime validity period
    scopes: IReadOnlySet<string>?
    The optional set of authorized scopes

    Retorna: An `ApiKeyIssuanceResult` containing the created API key entity and the plaintext key.

interface

IApiKeyStore

Ensamblado: EricksonLopez.Security.Abstractions
public interface IApiKeyStore

Defines repository operations for persisting, retrieving, and updating `ApiKey` entities.

Miembros (3)

  • methodGetByIdAsync
    ValueTask<Result<ApiKey>> GetByIdAsync(ApiKeyId keyId, CancellationToken cancellationToken = default)

    Retrieves an API key entity by its lookup identifier.

    keyId: ApiKeyId
    The unique lookup identifier of the API key
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` with the matching `ApiKey`, or a not-found error.

  • methodRevokeAsync
    ValueTask<Result> RevokeAsync(ApiKeyId keyId, CancellationToken cancellationToken = default)

    Revokes an existing API key.

    keyId: ApiKeyId
    The unique lookup identifier of the API key to revoke
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating whether the operation succeeded.

  • methodSaveAsync
    ValueTask<Result> SaveAsync(ApiKey apiKey, CancellationToken cancellationToken = default)

    Persists a newly issued API key entity.

    apiKey: ApiKey
    The API key entity to persist
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating whether the operation succeeded.

interface

IApiKeyValidator

Ensamblado: EricksonLopez.Security.Abstractions
public interface IApiKeyValidator

Defines contracts for validating presented API keys against persistent storage using constant-time comparison and active status checks.

Miembros (1)

  • methodValidateApiKeyAsync
    ValueTask<Result<ApiKey>> ValidateApiKeyAsync(string plaintextApiKey, CancellationToken cancellationToken = default)

    Validates an incoming plaintext API key against the registered API key store.

    plaintextApiKey: string
    The presented plaintext API key string to validate
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` with the validated `ApiKey` on success, or a failure error.

interface

IServiceCredentialEvaluator

Ensamblado: EricksonLopez.Security.Abstractions
public interface IServiceCredentialEvaluator

Evaluates incoming M2M service API keys in constant time against persisted `ServiceCredentialRecord` metadata, enforcing versioned HMAC proof-of-possession before status checks, rotation grace windows (`GraceUntilUtc`), and client IP CIDR allowlists.

Miembros (2)

  • methodEvaluate
    Result<ServiceCredentialRecord> Evaluate(ReadOnlySpan<char> rawApiKey, ServiceCredentialRecord? candidate, string? clientIpAddress = null)

    Evaluates a presented service API key against a candidate `ServiceCredentialRecord` (or `null` on store miss) with timing-equalized HMAC verification, revocation, expiration, rotation grace-window, and CIDR allowlist checks.

    rawApiKey: ReadOnlySpan<char>
    The raw service API key presented by the caller.
    candidate: ServiceCredentialRecord?
    The stored credential record resolved by prefix, or `null` when not found.
    clientIpAddress: string?
    Optional client IP address string evaluated when `ServiceCredentialRecord.AllowedCidrs` is non-empty.

    Retorna: A `Result<T>` containing the verified `ServiceCredentialRecord` on success, or a typed security error.

  • methodTryExtractKeyPrefix
    bool TryExtractKeyPrefix(ReadOnlySpan<char> rawApiKey, out string keyPrefix)

    Attempts to extract the indexed `{prefixTag}_{randomId8}` lookup prefix from a raw service API key.

    rawApiKey: ReadOnlySpan<char>
    The presented raw service API key.
    keyPrefix: out string
    When this method returns, contains the extracted key prefix if valid.

    Retorna: `true` if the credential matches the canonical structural format; otherwise, `false`.

interface

ITokenDenyList

Ensamblado: EricksonLopez.Security.Abstractions
public interface ITokenDenyList

Defines a fail-closed distributed token and principal revocation deny-list contract for immediate invalidation of compromised JWTs (`jti`) and active principal sessions.

Miembros (4)

  • methodDenyPrincipalAsync
    Task DenyPrincipalAsync(string principalId, TimeSpan ttl, CancellationToken cancellationToken = default)

    Globally revokes all active tokens for a principal identifier over the specified `ttl` window.

    principalId: string
    The unique user or service principal identifier.
    ttl: TimeSpan
    The revocation window duration (must cover maximum token lifetime).
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A task representing the asynchronous principal revocation write.

    Exceptions: TokenRevocationStoreUnavailableException: The underlying revocation store is unreachable.

  • methodDenyTokenAsync
    Task DenyTokenAsync(string jti, TimeSpan ttl, CancellationToken cancellationToken = default)

    Adds a specific token identifier (`jti`) to the revocation deny-list for its remaining time-to-live.

    jti: string
    The unique token identifier (`jti`).
    ttl: TimeSpan
    The time-to-live duration for the revocation entry.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A task representing the asynchronous revocation write.

    Exceptions: TokenRevocationStoreUnavailableException: The underlying revocation store is unreachable.

  • methodIsPrincipalDeniedAsync
    Task<bool> IsPrincipalDeniedAsync(string principalId, CancellationToken cancellationToken = default)

    Determines whether a principal identifier is currently subject to global token revocation. Implementations must enforce fail-closed semantics: empty `principalId` returns `true`, and store connectivity failures throw `TokenRevocationStoreUnavailableException`.

    principalId: string
    The unique user or service principal identifier.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: `true` if the principal is denied or empty; otherwise, `false`.

    Exceptions: TokenRevocationStoreUnavailableException: The underlying revocation store is unreachable.

  • methodIsTokenDeniedAsync
    Task<bool> IsTokenDeniedAsync(string jti, CancellationToken cancellationToken = default)

    Determines whether a specific token identifier (`jti`) has been revoked. Implementations must enforce fail-closed semantics: empty `jti` returns `true`, and store connectivity failures throw `TokenRevocationStoreUnavailableException`.

    jti: string
    The unique token identifier (`jti`).
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: `true` if the token is denied or missing a valid identifier; otherwise, `false`.

    Exceptions: TokenRevocationStoreUnavailableException: The underlying revocation store is unreachable.

interface

ITokenGenerator

Ensamblado: EricksonLopez.Security.Abstractions
public interface ITokenGenerator

Defines contracts for generating high-entropy, cryptographically random opaque tokens.

Miembros (6)

  • methodGenerateHexToken
    string GenerateHexToken(int byteLength = 32)

    Generates a cryptographically secure hex-encoded token string.

    byteLength: int
    The number of random bytes to generate, defaulting to 32 bytes

    Retorna: A lowercase hex-encoded token string.

  • methodGenerateNumericCode
    string GenerateNumericCode(int digits = 6)

    Generates a cryptographically secure numeric code of the specified digit length.

    digits: int
    The number of digits in the generated code, defaulting to 6

    Retorna: A numeric code string of the specified length.

  • methodGenerateToken
    OpaqueToken GenerateToken(int byteLength = 32)

    Generates a cryptographically secure opaque token with the specified entropy byte length.

    byteLength: int
    The number of random bytes to generate, defaulting to 32 bytes

    Retorna: A new `OpaqueToken` containing the generated random bytes.

  • methodGenerateTokenSecretBuffer
    ISecretBuffer GenerateTokenSecretBuffer(int byteLength = 32)

    Generates a cryptographically secure token and stores its raw bytes in a zeroizable secret buffer.

    byteLength: int
    The number of random bytes to generate, defaulting to 32 bytes.

    Retorna: A zeroizable `ISecretBuffer` containing the generated random bytes.

  • methodGenerateUrlSafeToken
    string GenerateUrlSafeToken(int byteLength = 32)

    Generates a cryptographically secure URL-safe base64-encoded token string.

    byteLength: int
    The number of random bytes to generate, defaulting to 32 bytes

    Retorna: A URL-safe token string.

  • methodTryGenerateUrlSafeToken
    bool TryGenerateUrlSafeToken(Span<char> destination, int byteLength, out int charsWritten)

    Attempts to generate a cryptographically secure URL-safe token into the specified destination span.

    destination: Span<char>
    The destination span for the generated token characters.
    byteLength: int
    The number of random bytes to generate, defaulting to 32 bytes.
    charsWritten: out int
    The number of characters written to the destination span.

    Retorna: `true` if the token was successfully generated; otherwise, `false`.

interface

ITokenHasher

Ensamblado: EricksonLopez.Security.Abstractions
public interface ITokenHasher

Defines contracts for deterministic and salted cryptographic hashing of security tokens.

Miembros (2)

  • methodHashToken
    string HashToken(ReadOnlySpan<char> token)

    Computes a deterministic cryptographic hash of the token suitable for indexed database lookups.

    token: ReadOnlySpan<char>
    The token character span to hash

    Retorna: A hex-encoded or base64-encoded hash digest of the token.

  • methodVerifyToken
    bool VerifyToken(ReadOnlySpan<char> token, string expectedHash)

    Verifies a candidate token against an expected hash using constant-time evaluation.

    token: ReadOnlySpan<char>
    The candidate token character span to verify
    expectedHash: string
    The expected token hash to compare against

    Retorna: `true` if the candidate token matches the expected hash; otherwise, `false`.

interface

IVersionedCredentialHmacService

Ensamblado: EricksonLopez.Security.Abstractions
public interface IVersionedCredentialHmacService

Defines a versioned, domain-separated HMAC-SHA256 credential hashing and issuance service using HKDF-SHA256 subkeys derived per pepper version and credential domain purpose.

Miembros (8)

  • methodComputeBackupCodeHmac
    string ComputeBackupCodeHmac(ReadOnlySpan<char> rawBackupCode, int? pepperVersion = null)

    Computes the domain-separated 64-character lowercase hexadecimal HMAC-SHA256 digest of a backup code after stripping formatting delimiters and normalizing to uppercase alphanumeric characters.

    rawBackupCode: ReadOnlySpan<char>
    The raw user-supplied backup code.
    pepperVersion: int?
    Optional pepper version (`null` uses `ActivePepperVersion`).

    Retorna: A 64-character lowercase hexadecimal HMAC-SHA256 digest.

  • methodComputeHmac
    string ComputeHmac(string domainPurpose, ReadOnlySpan<char> credential, int? pepperVersion = null)

    Computes a domain-separated 64-character lowercase hexadecimal HMAC-SHA256 digest for a high-entropy credential.

    domainPurpose: string
    The non-empty domain purpose label (for example, `"service-credential"` or `"refresh-token"`).
    credential: ReadOnlySpan<char>
    The raw credential characters.
    pepperVersion: int?
    Optional pepper version (`null` uses `ActivePepperVersion`).

    Retorna: A 64-character lowercase hexadecimal HMAC-SHA256 digest, or 64 zeros if `credential` is empty or whitespace.

  • methodComputeServiceCredentialHmac
    string ComputeServiceCredentialHmac(ReadOnlySpan<char> rawApiKey, int? pepperVersion = null)

    Computes the domain-separated HMAC-SHA256 digest of a full service API key for indexed lookup or verification.

    rawApiKey: ReadOnlySpan<char>
    The raw service API key.
    pepperVersion: int?
    Optional pepper version (`null` uses `ActivePepperVersion`).

    Retorna: A 64-character lowercase hexadecimal HMAC-SHA256 digest.

  • methodGenerateBackupCodes
    IReadOnlyList<GeneratedBackupCode> GenerateBackupCodes(int count = 8)

    Generates a set of unique, unambiguous single-use emergency backup codes formatted as `XXXX-XXXX-XXXX` paired with their normalized domain-separated HMAC-SHA256 digests.

    count: int
    The number of unique backup codes to generate (default 8).

    Retorna: An immutable list of `GeneratedBackupCode` entries.

  • methodIssueServiceCredential
    IssuedServiceCredential IssueServiceCredential(string prefixTag = "")

    Issues a structured M2M service API key (`{prefixTag}_{randomId8}_{base64UrlSecret}`) with 256 bits of CSPRNG entropy, scrubbing the raw secret byte buffer before returning.

    prefixTag: string
    The environment-qualified key prefix tag (for example, `"sk_live"` or `"sk_test"`).

    Retorna: An `IssuedServiceCredential` containing the one-time plaintext key, lookup prefix, HMAC digest, and pepper version.

  • methodVerifyBackupCode
    bool VerifyBackupCode(ReadOnlySpan<char> rawBackupCode, ReadOnlySpan<char> expectedHexDigest, int? pepperVersion = null)

    Verifies a user-supplied backup code against a stored 64-character hexadecimal HMAC-SHA256 digest in constant time.

    rawBackupCode: ReadOnlySpan<char>
    The raw user-supplied backup code.
    expectedHexDigest: ReadOnlySpan<char>
    The stored 64-character hexadecimal HMAC-SHA256 digest.
    pepperVersion: int?
    Optional pepper version stored alongside the backup code.

    Retorna: `true` if the normalized backup code matches `expectedHexDigest`; otherwise, `false`.

  • methodVerifyHmac
    bool VerifyHmac(string domainPurpose, ReadOnlySpan<char> credential, ReadOnlySpan<char> expectedHexDigest, int? pepperVersion = null)

    Verifies a raw credential against an expected 64-character hexadecimal HMAC-SHA256 digest in constant time.

    domainPurpose: string
    The non-empty domain purpose label.
    credential: ReadOnlySpan<char>
    The raw credential characters presented by the caller.
    expectedHexDigest: ReadOnlySpan<char>
    The stored 64-character hexadecimal HMAC-SHA256 digest.
    pepperVersion: int?
    Optional pepper version stored alongside the credential.

    Retorna: `true` if the credential matches `expectedHexDigest`; otherwise, `false`.

  • propertyActivePepperVersion
    int ActivePepperVersion { get; }

    Gets the currently active server pepper version used when issuing or hashing new credentials.

record

IssuedServiceCredential

Ensamblado: EricksonLopez.Security.Abstractions
public readonly record struct IssuedServiceCredential(string PlaintextCredential, string KeyPrefix, string SecretHmacHex, int PepperVersion)

Represents a newly issued machine-to-machine (M2M) service credential containing the one-time plaintext API key, indexed lookup prefix, domain-separated HMAC-SHA256 digest, and pepper version.

Miembros (5)

  • constructorIssuedServiceCredential
    public IssuedServiceCredential(string PlaintextCredential, string KeyPrefix, string SecretHmacHex, int PepperVersion)

    Initializes a new instance of IssuedServiceCredential.

    PlaintextCredential: string
    The full plaintext credential (`{prefixTag}_{randomId8}_{base64UrlSecret}`) shown once at issuance.
    KeyPrefix: string
    The public indexed key prefix (`{prefixTag}_{randomId8}`) safe for lookup and display.
    SecretHmacHex: string
    The 64-character lowercase hexadecimal HMAC-SHA256 digest of the full credential.
    PepperVersion: int
    The server HMAC pepper version used to compute `SecretHmacHex`.
  • propertyKeyPrefix
    public string KeyPrefix { get; init; }

    The public indexed key prefix (`{prefixTag}_{randomId8}`) safe for lookup and display.

  • propertyPepperVersion
    public int PepperVersion { get; init; }

    The server HMAC pepper version used to compute `SecretHmacHex`.

  • propertyPlaintextCredential
    public string PlaintextCredential { get; init; }

    The full plaintext credential (`{prefixTag}_{randomId8}_{base64UrlSecret}`) shown once at issuance.

  • propertySecretHmacHex
    public string SecretHmacHex { get; init; }

    The 64-character lowercase hexadecimal HMAC-SHA256 digest of the full credential.

record

ServiceCredentialRecord

Ensamblado: EricksonLopez.Security.Abstractions
public sealed record ServiceCredentialRecord(string CredentialId, string PrincipalId, string KeyPrefix, string SecretHmacHex, int PepperVersion, DateTimeOffset ExpiresAtUtc, DateTimeOffset? GraceUntilUtc, bool IsRevoked, IReadOnlyList<string>? AllowedCidrs, string? TenantId, string? CompanyId, IReadOnlyList<string>? Scopes)

Represents persisted metadata for a machine-to-machine (M2M) service credential evaluated during authentication, supporting versioned HMAC peppers, rotation grace windows (`GraceUntilUtc`), and CIDR network allowlists.

Miembros (13)

  • constructorServiceCredentialRecord
    public ServiceCredentialRecord(string CredentialId, string PrincipalId, string KeyPrefix, string SecretHmacHex, int PepperVersion, DateTimeOffset ExpiresAtUtc, DateTimeOffset? GraceUntilUtc = null, bool IsRevoked = false, IReadOnlyList<string>? AllowedCidrs = null, string? TenantId = null, string? CompanyId = null, IReadOnlyList<string>? Scopes = null)

    Initializes a new instance of ServiceCredentialRecord.

    CredentialId: string
    Unique identifier of the service credential.
    PrincipalId: string
    Unique identifier of the owning service principal.
    KeyPrefix: string
    Indexed public credential prefix (`{prefixTag}_{randomId8}`).
    SecretHmacHex: string
    Stored 64-character hexadecimal HMAC-SHA256 digest of the credential.
    PepperVersion: int
    Server HMAC pepper version used when computing `SecretHmacHex`.
    ExpiresAtUtc: DateTimeOffset
    Absolute UTC expiration timestamp of the credential.
    GraceUntilUtc: DateTimeOffset?
    Optional UTC grace-window deadline applied to rotated credentials.
    IsRevoked: bool
    Indicates whether the credential or its owning principal has been revoked or suspended.
    AllowedCidrs: IReadOnlyList<string>?
    Optional list of CIDR blocks allowed to present this credential.
    TenantId: string?
    Optional tenant scope bound to the service principal.
    CompanyId: string?
    Optional company or organization unit scope bound to the service principal.
    Scopes: IReadOnlyList<string>?
    Optional permission or scope codes granted to the service principal.
  • propertyAllowedCidrs
    public IReadOnlyList<string>? AllowedCidrs { get; init; }

    Optional list of CIDR blocks allowed to present this credential.

  • propertyCompanyId
    public string? CompanyId { get; init; }

    Optional company or organization unit scope bound to the service principal.

  • propertyCredentialId
    public string CredentialId { get; init; }

    Unique identifier of the service credential.

  • propertyExpiresAtUtc
    public DateTimeOffset ExpiresAtUtc { get; init; }

    Absolute UTC expiration timestamp of the credential.

  • propertyGraceUntilUtc
    public DateTimeOffset? GraceUntilUtc { get; init; }

    Optional UTC grace-window deadline applied to rotated credentials.

  • propertyIsRevoked
    public bool IsRevoked { get; init; }

    Indicates whether the credential or its owning principal has been revoked or suspended.

  • propertyKeyPrefix
    public string KeyPrefix { get; init; }

    Indexed public credential prefix (`{prefixTag}_{randomId8}`).

  • propertyPepperVersion
    public int PepperVersion { get; init; }

    Server HMAC pepper version used when computing `SecretHmacHex`.

  • propertyPrincipalId
    public string PrincipalId { get; init; }

    Unique identifier of the owning service principal.

  • propertyScopes
    public IReadOnlyList<string>? Scopes { get; init; }

    Optional permission or scope codes granted to the service principal.

  • propertySecretHmacHex
    public string SecretHmacHex { get; init; }

    Stored 64-character hexadecimal HMAC-SHA256 digest of the credential.

  • propertyTenantId
    public string? TenantId { get; init; }

    Optional tenant scope bound to the service principal.

class

TokenRevocationStoreUnavailableException

Ensamblado: EricksonLopez.Security.Abstractions
public sealed class TokenRevocationStoreUnavailableException : Exception
Hereda de: Exception

Exception thrown when the distributed token revocation store is unreachable, signaling authentication and authorization middleware to enforce a strict fail-closed HTTP `503 Service Unavailable` response.

Miembros (3)

  • constructorTokenRevocationStoreUnavailableException
    public TokenRevocationStoreUnavailableException()

    Initializes a new instance of the `TokenRevocationStoreUnavailableException` class.

  • constructorTokenRevocationStoreUnavailableException
    public TokenRevocationStoreUnavailableException(string message)

    Initializes a new instance of the `TokenRevocationStoreUnavailableException` class with a custom message.

    message: string
    The error message describing the outage.
  • constructorTokenRevocationStoreUnavailableException
    public TokenRevocationStoreUnavailableException(string message, Exception innerException)

    Initializes a new instance of the `TokenRevocationStoreUnavailableException` class with a custom message and inner exception.

    message: string
    The error message describing the outage.
    innerException: Exception
    The underlying storage connectivity exception.

EricksonLopez.Security.Analyzers#

6
class

DiagnosticIds

Ensamblado: EricksonLopez.Security.Analyzers
public static class DiagnosticIds

Provides diagnostic identifier constants for the EricksonLopez.Security Roslyn analyzers.

Miembros (5)

  • fieldHardcodedSecret
    public const string HardcodedSecret

    Represents the diagnostic identifier reported when hardcoded cryptographic keys or secrets are detected in source code (ELS0003).

  • fieldInsecurePasswordAlgorithm
    public const string InsecurePasswordAlgorithm

    Represents the diagnostic identifier reported when insecure or deprecated password hashing algorithms are utilized (ELS0004).

  • fieldLoggingRawSecret
    public const string LoggingRawSecret

    Represents the diagnostic identifier reported when sensitive cryptographic material is passed unredacted to logging sinks (ELS0005).

  • fieldNonConstantTimeComparison
    public const string NonConstantTimeComparison

    Represents the diagnostic identifier reported when string or sequence equality comparisons are performed without constant-time guarantees (ELS0001).

  • fieldUndisposedSecretBuffer
    public const string UndisposedSecretBuffer

    Represents the diagnostic identifier reported when a secret buffer is instantiated without proper disposal (ELS0002).

class

HardcodedSecretAnalyzer

Ensamblado: EricksonLopez.Security.Analyzers
public sealed class HardcodedSecretAnalyzer : DiagnosticAnalyzer
Hereda de: DiagnosticAnalyzer

Represents a diagnostic analyzer that detects hardcoded string literals assigned to variables with security-sensitive names.

Miembros (2)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Gets a set of descriptors for the diagnostic rules that this analyzer is capable of producing.

class

InsecurePasswordAlgorithmAnalyzer

Ensamblado: EricksonLopez.Security.Analyzers
public sealed class InsecurePasswordAlgorithmAnalyzer : DiagnosticAnalyzer
Hereda de: DiagnosticAnalyzer

Represents a diagnostic analyzer that detects the use of insecure or deprecated algorithms for password hashing.

Miembros (2)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Gets a set of descriptors for the diagnostic rules that this analyzer is capable of producing.

class

LoggingRawSecretAnalyzer

Ensamblado: EricksonLopez.Security.Analyzers
public sealed class LoggingRawSecretAnalyzer : DiagnosticAnalyzer
Hereda de: DiagnosticAnalyzer

Represents a diagnostic analyzer that detects when security-sensitive values are logged without redaction.

Miembros (2)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Gets a set of descriptors for the diagnostic rules that this analyzer is capable of producing.

class

NonConstantTimeComparisonAnalyzer

Ensamblado: EricksonLopez.Security.Analyzers
public sealed class NonConstantTimeComparisonAnalyzer : DiagnosticAnalyzer
Hereda de: DiagnosticAnalyzer

Represents a diagnostic analyzer that detects non-constant-time equality comparisons on security-sensitive values.

Notas:

Identifies expressions where equality operators (`==` or `!=`) are used on operands whose names indicate cryptographic tokens, keys, hashes, or passwords, recommending constant-time alternatives to mitigate side-channel timing attacks.

Miembros (2)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Gets a set of descriptors for the diagnostic rules that this analyzer is capable of producing.

class

UndisposedSecretBufferAnalyzer

Ensamblado: EricksonLopez.Security.Analyzers
public sealed class UndisposedSecretBufferAnalyzer : DiagnosticAnalyzer
Hereda de: DiagnosticAnalyzer

Represents a diagnostic analyzer that detects secret buffers that are not properly disposed.

Notas:

Ensures that instances of `SecretBuffer` are scoped within using statements or explicitly disposed to guarantee that sensitive memory is zeroed upon disposal.

Miembros (2)

  • methodInitialize
    public override void Initialize(AnalysisContext context)

    Inherits documentation from base type or interface.

    context: AnalysisContext
  • propertySupportedDiagnostics
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }

    Gets a set of descriptors for the diagnostic rules that this analyzer is capable of producing.

EricksonLopez.Security.Approvals#

3
interface

IMakerCheckerGrantValidator

Ensamblado: EricksonLopez.Security
public interface IMakerCheckerGrantValidator

Issues and validates cryptographic Maker-Checker approval grants enforcing `ApproverId != ActorId`, company isolation, operation scope binding, and short-lived expiration.

Miembros (3)

  • methodIssueGrant
    Result<string> IssueGrant(Guid approverId, Guid actorId, Guid companyId, string scope, TimeSpan? ttl = null)

    Issues a signed short-lived Maker-Checker approval grant token for an authorized approver distinct from the requesting actor.

    approverId: Guid
    The authenticated supervisor/approver user identifier.
    actorId: Guid
    The requesting operator user identifier (must differ from `approverId`).
    companyId: Guid
    The company identifier scoping the operation.
    scope: string
    The required operation scope (for example, `"sales:sell-below-cost"`).
    ttl: TimeSpan?
    Optional custom grant time-to-live (defaults to 5 minutes).

    Retorna: A signed compact grant token string on success; otherwise, a validation or forbidden error.

  • methodValidate
    Result<VerifiedApprovalGrant> Validate(ReadOnlySpan<char> token, Guid actorId, Guid companyId, string requiredScope)

    Validates a signed Maker-Checker approval grant token synchronously in constant time.

    token: ReadOnlySpan<char>
    The compact signed approval token.
    actorId: Guid
    The requesting operator user identifier executing the guarded action.
    companyId: Guid
    The active company identifier.
    requiredScope: string
    The required operation scope.

    Retorna: The verified `VerifiedApprovalGrant` on success; otherwise, an unauthorized, forbidden, or validation error.

  • methodValidateAsync
    ValueTask<Result<VerifiedApprovalGrant>> ValidateAsync(string token, Guid actorId, Guid companyId, string requiredScope, CancellationToken ct = default)

    Validates a signed Maker-Checker approval grant token asynchronously.

    token: string
    The compact signed approval token.
    actorId: Guid
    The requesting operator user identifier executing the guarded action.
    companyId: Guid
    The active company identifier.
    requiredScope: string
    The required operation scope.
    ct: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A value task containing the verified `VerifiedApprovalGrant` on success; otherwise, an error.

class

MakerCheckerGrantValidator

Ensamblado: EricksonLopez.Security
public sealed class MakerCheckerGrantValidator : IMakerCheckerGrantValidator, IDisposable
Implementa: IDisposable, IMakerCheckerGrantValidator

Default HMAC-SHA256 implementation of `IMakerCheckerGrantValidator` enforcing strict dual-control separation of duties (`ApproverId != ActorId`), company isolation, scope binding, and RFC 4648 §3.5 canonical Base64Url MAC verification.

Miembros (5)

  • constructorMakerCheckerGrantValidator
    public MakerCheckerGrantValidator(ReadOnlySpan<byte> signingKey, TimeProvider? timeProvider = null)

    Initializes a new instance of the `MakerCheckerGrantValidator` class with a 256-bit+ signing key.

    signingKey: ReadOnlySpan<byte>
    The secret HMAC-SHA256 signing key (at least 32 bytes).
    timeProvider: TimeProvider?
    Optional time provider.

    Exceptions: ArgumentException: `signingKey` is shorter than 32 bytes.

  • methodDispose
    public void Dispose()

    Inherits documentation from base type or interface.

  • methodIssueGrant
    public Result<string> IssueGrant(Guid approverId, Guid actorId, Guid companyId, string scope, TimeSpan? ttl = null)

    Issues a signed short-lived Maker-Checker approval grant token for an authorized approver distinct from the requesting actor.

    approverId: Guid
    The authenticated supervisor/approver user identifier.
    actorId: Guid
    The requesting operator user identifier (must differ from `approverId`).
    companyId: Guid
    The company identifier scoping the operation.
    scope: string
    The required operation scope (for example, `"sales:sell-below-cost"`).
    ttl: TimeSpan?
    Optional custom grant time-to-live (defaults to 5 minutes).

    Retorna: A signed compact grant token string on success; otherwise, a validation or forbidden error.

  • methodValidate
    public Result<VerifiedApprovalGrant> Validate(ReadOnlySpan<char> token, Guid actorId, Guid companyId, string requiredScope)

    Validates a signed Maker-Checker approval grant token synchronously in constant time.

    token: ReadOnlySpan<char>
    The compact signed approval token.
    actorId: Guid
    The requesting operator user identifier executing the guarded action.
    companyId: Guid
    The active company identifier.
    requiredScope: string
    The required operation scope.

    Retorna: The verified `VerifiedApprovalGrant` on success; otherwise, an unauthorized, forbidden, or validation error.

  • methodValidateAsync
    public ValueTask<Result<VerifiedApprovalGrant>> ValidateAsync(string token, Guid actorId, Guid companyId, string requiredScope, CancellationToken ct = default)

    Validates a signed Maker-Checker approval grant token asynchronously.

    token: string
    The compact signed approval token.
    actorId: Guid
    The requesting operator user identifier executing the guarded action.
    companyId: Guid
    The active company identifier.
    requiredScope: string
    The required operation scope.
    ct: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A value task containing the verified `VerifiedApprovalGrant` on success; otherwise, an error.

record

VerifiedApprovalGrant

Ensamblado: EricksonLopez.Security
public sealed record VerifiedApprovalGrant(Guid GrantId, Guid CompanyId, Guid ApproverId, Guid ActorId, string Scope, DateTimeOffset IssuedAtUtc, DateTimeOffset ExpiresAtUtc)

Represents a cryptographically verified Maker-Checker supervisor approval grant bound to an explicit actor, approver, company, scope, and expiration window.

Miembros (8)

  • constructorVerifiedApprovalGrant
    public VerifiedApprovalGrant(Guid GrantId, Guid CompanyId, Guid ApproverId, Guid ActorId, string Scope, DateTimeOffset IssuedAtUtc, DateTimeOffset ExpiresAtUtc)

    Initializes a new instance of VerifiedApprovalGrant.

    GrantId: Guid
    The unique grant identifier (UUIDv7).
    CompanyId: Guid
    The isolated company identifier to which this grant is bound.
    ApproverId: Guid
    The authenticated supervisor/approver user identifier (guaranteed distinct from `ActorId`).
    ActorId: Guid
    The requesting operator user identifier.
    Scope: string
    The normalized operation scope authorized by this grant.
    IssuedAtUtc: DateTimeOffset
    The UTC timestamp at which the grant was signed.
    ExpiresAtUtc: DateTimeOffset
    The UTC expiration timestamp after which the grant is rejected.
  • propertyActorId
    public Guid ActorId { get; init; }

    The requesting operator user identifier.

  • propertyApproverId
    public Guid ApproverId { get; init; }

    The authenticated supervisor/approver user identifier (guaranteed distinct from `ActorId`).

  • propertyCompanyId
    public Guid CompanyId { get; init; }

    The isolated company identifier to which this grant is bound.

  • propertyExpiresAtUtc
    public DateTimeOffset ExpiresAtUtc { get; init; }

    The UTC expiration timestamp after which the grant is rejected.

  • propertyGrantId
    public Guid GrantId { get; init; }

    The unique grant identifier (UUIDv7).

  • propertyIssuedAtUtc
    public DateTimeOffset IssuedAtUtc { get; init; }

    The UTC timestamp at which the grant was signed.

  • propertyScope
    public string Scope { get; init; }

    The normalized operation scope authorized by this grant.

EricksonLopez.Security.AspNetCore.Authentication#

3
class

ApiKeyAuthenticationHandler

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthenticationOptions>
Hereda de: AuthenticationHandler<ApiKeyAuthenticationOptions>

Provides a native ASP.NET Core AuthenticationHandler for API Keys.

Miembros (2)

  • constructorApiKeyAuthenticationHandler
    public ApiKeyAuthenticationHandler(IOptionsMonitor<ApiKeyAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, IApiKeyValidator validator)

    Initializes a new instance of the `ApiKeyAuthenticationHandler` class.

    options: IOptionsMonitor<ApiKeyAuthenticationOptions>
    The monitor for the options instance.
    logger: ILoggerFactory
    The factory used to create loggers.
    encoder: UrlEncoder
    The URL encoder.
    validator: IApiKeyValidator
    The API key validator service.

    Exceptions: ArgumentNullException: `validator` is `null`

  • fieldHttpContextApiKeyItemKey
    public const string HttpContextApiKeyItemKey

    Specifies the `HttpContext.Items` key that stores the authenticated API key entity.

class

ApiKeyAuthenticationMiddleware

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class ApiKeyAuthenticationMiddleware

Provides middleware that intercepts HTTP requests, extracts API keys from headers or query parameters, validates them against the registered `IApiKeyValidator`, and assigns a validated `ClaimsPrincipal` to `HttpContext.User`.

Miembros (3)

  • constructorApiKeyAuthenticationMiddleware
    public ApiKeyAuthenticationMiddleware(RequestDelegate next, IOptions<ApiKeyAuthenticationOptions> options)

    Initializes a new instance of the `ApiKeyAuthenticationMiddleware` class.

    next: RequestDelegate
    The next middleware delegate in the HTTP request pipeline.
    options: IOptions<ApiKeyAuthenticationOptions>
    The configured API key authentication options accessor.

    Exceptions: ArgumentNullException: `next` is `null`

  • methodInvokeAsync
    public async Task InvokeAsync(HttpContext context, IApiKeyValidator validator)

    Processes an HTTP request to authenticate the caller via API key.

    context: HttpContext
    The current HTTP context for the request.
    validator: IApiKeyValidator
    The API key validation service.

    Retorna: A task representing the asynchronous operation.

    Exceptions: ArgumentNullException: `context` or `validator` is `null`

  • fieldHttpContextApiKeyItemKey
    public const string HttpContextApiKeyItemKey

    Specifies the key for storing the authenticated `ApiKey` instance in `HttpContext.Items`.

class

ApiKeyAuthenticationOptions

Ensamblado: EricksonLopez.Security.AspNetCore
public class ApiKeyAuthenticationOptions : AuthenticationSchemeOptions
Hereda de: AuthenticationSchemeOptions

Specifies configuration options for HTTP API key authentication middleware and extraction.

Miembros (6)

  • propertyAllowedHeaderPathPrefixes
    public IList<string> AllowedHeaderPathPrefixes { get; }

    Gets optional path prefixes (for example, `"/api/v1/integrations"` or `"/scim/v2"`) where custom `HeaderName` extraction is permitted. When empty (default), `HeaderName` is accepted on all paths; `Authorization: ApiKey <token>` is always accepted.

  • propertyAuthenticationScheme
    public string AuthenticationScheme { get; set; }

    Gets or sets the authentication scheme name (default: "ApiKey").

  • propertyHeaderName
    public string HeaderName { get; set; }

    Gets or sets the HTTP request header name for passing API keys (default: "X-Api-Key").

  • propertyRequireApiKey
    public bool RequireApiKey { get; set; }

    Gets or sets a value indicating whether requests missing an API key should return 401 Unauthorized immediately.

    The default value is `true` to enforce secure-by-default behavior.

  • propertyRetryAfterSeconds
    public int RetryAfterSeconds { get; set; }

    Gets or sets the `Retry-After` header value (in seconds) returned when revocation infrastructure is unavailable (`503`). Default: `5`.

  • propertyUseProblemDetailsResponses
    public bool UseProblemDetailsResponses { get; set; }

    Gets or sets a value indicating whether challenges emit RFC 7807 `application/problem+json` responses (`401` and fail-closed `503`). Default: `false`.

EricksonLopez.Security.AspNetCore.Authorization#

12
class

AssuranceLevelAuthorizationHandler

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class AssuranceLevelAuthorizationHandler : AuthorizationHandler<AssuranceLevelRequirement>
Hereda de: AuthorizationHandler<AssuranceLevelRequirement>

Evaluates `AssuranceLevelRequirement` against the principal's `aal` claim, stamping `AuthorizationFailureConstants.StepUpMfaRequired` when step-up MFA assurance is insufficient.

Miembros (1)

  • constructorAssuranceLevelAuthorizationHandler
    public AssuranceLevelAuthorizationHandler(IHttpContextAccessor? httpContextAccessor = null)

    Initializes a new instance of the `AssuranceLevelAuthorizationHandler` class.

    httpContextAccessor: IHttpContextAccessor?
    Optional HTTP context accessor used to record failure reason codes.
record

AssuranceLevelRequirement

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed record AssuranceLevelRequirement(AuthenticationAssuranceLevel MinimumAssuranceLevel) : IAuthorizationRequirement
Implementa: IAuthorizationRequirement

Authorization requirement enforcing a minimum NIST SP 800-63B `AuthenticationAssuranceLevel` (for example, `AAL2` step-up MFA).

Miembros (2)

  • constructorAssuranceLevelRequirement
    public AssuranceLevelRequirement(AuthenticationAssuranceLevel MinimumAssuranceLevel)

    Initializes a new instance of AssuranceLevelRequirement.

    MinimumAssuranceLevel: AuthenticationAssuranceLevel
    The minimum required `AuthenticationAssuranceLevel`.
  • propertyMinimumAssuranceLevel
    public AuthenticationAssuranceLevel MinimumAssuranceLevel { get; init; }

    The minimum required `AuthenticationAssuranceLevel`.

class

AuthorizationFailureConstants

Ensamblado: EricksonLopez.Security.AspNetCore
public static class AuthorizationFailureConstants

Defines canonical `HttpContext.Items` keys and machine-readable authorization failure codes used across Zero-Trust authentication and authorization handlers.

Miembros (13)

  • fieldControlPlaneContaminated
    public const string ControlPlaneContaminated

    Failure code emitted when a `CONTROL` plane token is contaminated with tenant or company claims.

  • fieldFailureCodeItemKey
    public const string FailureCodeItemKey

    `HttpContext.Items` key storing the machine-readable authorization failure code.

  • fieldImpersonationForbidden
    public const string ImpersonationForbidden

    Failure code emitted when an operation is prohibited during a delegated support impersonation session.

  • fieldInfrastructureUnavailableItemKey
    public const string InfrastructureUnavailableItemKey

    `HttpContext.Items` key flagging fail-closed authentication/revocation infrastructure unavailability (`503`).

  • fieldInvalidApiKey
    public const string InvalidApiKey

    Failure code emitted when an M2M API credential is missing, malformed, revoked, or expired.

  • fieldInvalidTokenScope
    public const string InvalidTokenScope

    Failure code emitted when a token's `scope` / `token_use` claim does not match the endpoint's bounded purpose.

  • fieldMembershipSuspended
    public const string MembershipSuspended

    Failure code emitted when a principal account or membership is suspended or revoked.

  • fieldPermissionRevoked
    public const string PermissionRevoked

    Failure code emitted when the principal lacks the required permission code.

  • fieldSecurityPlaneForbidden
    public const string SecurityPlaneForbidden

    Failure code emitted when a principal attempts to cross `CONTROL`, `TENANT`, or `M2M` plane boundaries.

  • fieldServiceUnavailable
    public const string ServiceUnavailable

    Failure code emitted when revocation or authorization infrastructure is unreachable (`503`).

  • fieldStepUpMfaRequired
    public const string StepUpMfaRequired

    Failure code emitted when an operation requires elevated multi-factor assurance (`AAL2+`).

  • fieldTenantContextMissing
    public const string TenantContextMissing

    Failure code emitted when a `TENANT` or `M2M` principal lacks mandatory tenant or organization scope claims.

  • fieldTenantSuspended
    public const string TenantSuspended

    Failure code emitted when the target tenant or organization unit is suspended or inactive.

class

BoundedAuthSchemeNames

Ensamblado: EricksonLopez.Security.AspNetCore
public static class BoundedAuthSchemeNames

Defines canonical authentication scheme names for purpose-bounded JWT bearer and M2M API key pipelines.

Miembros (6)

  • fieldAllHumanBearerSchemes
    public const string AllHumanBearerSchemes

    Comma-delimited list of all human JWT authentication schemes.

  • fieldApiKey
    public const string ApiKey

    Machine-to-machine (M2M) service credential authentication scheme (`scope = "m2m"`).

  • fieldBearer
    public const string Bearer

    Operational human session RS256 access token scheme (`scope = "access"`).

  • fieldMfaChallengeBearer
    public const string MfaChallengeBearer

    Pre-authentication MFA challenge RS256 token scheme (`scope = "pre_auth:mfa"`).

  • fieldOnboardingBearer
    public const string OnboardingBearer

    Pre-authentication onboarding RS256 token scheme (`scope = "pre_auth:onboarding"`).

  • fieldTenantSelectionBearer
    public const string TenantSelectionBearer

    Pre-authentication multi-tenant selection RS256 token scheme (`scope = "pre_auth:tenant_selection"`).

class

GenerationalPermissionCache

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class GenerationalPermissionCache : IGenerationalPermissionCache
Implementa: IGenerationalPermissionCache

Provides a two-tier (L1 `IMemoryCache` + L2 `IDistributedCache`) permission snapshot cache with atomic local generational invalidation, O(1) distributed principal/tenant epoch bumping, per-key stampede locks, live evaluation bypass for delegated/impersonated sessions, and strict fail-closed `PermissionSnapshot.Deny` fallback.

Miembros (6)

  • constructorGenerationalPermissionCache
    public GenerationalPermissionCache(IPermissionSnapshotSource source, IMemoryCache l1Cache, IDistributedCache l2Cache, IOptions<GenerationalPermissionCacheOptions>? options = null, ILogger<GenerationalPermissionCache>? logger = null)

    Initializes a new instance of the `GenerationalPermissionCache` class.

    source: IPermissionSnapshotSource
    The authoritative permission snapshot source.
    l1Cache: IMemoryCache
    The in-process L1 memory cache.
    l2Cache: IDistributedCache
    The distributed L2 cache.
    options: IOptions<GenerationalPermissionCacheOptions>?
    Optional cache configuration options.
    logger: ILogger<GenerationalPermissionCache>?
    Optional structured logger.

    Exceptions: ArgumentNullException: Any required dependency is `null`.

  • methodGetEffectiveSnapshotAsync
    public async ValueTask<PermissionSnapshot> GetEffectiveSnapshotAsync(PermissionScopeKey key, CancellationToken cancellationToken = default)

    Resolves the effective `PermissionSnapshot` for `key` using generational L1+L2 caching, bypassing caches for delegated/impersonated sessions, and returning `PermissionSnapshot.Deny` on failure.

    key: PermissionScopeKey
    The multi-plane permission scope key.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A value task containing the effective `PermissionSnapshot`.

  • methodInvalidateLocalGeneration
    public void InvalidateLocalGeneration()

    Immediately bumps the local L1 in-memory generation counter so subsequent reads re-verify against L2 epochs.

  • methodInvalidatePrincipalAsync
    public async ValueTask InvalidatePrincipalAsync(string principalId, CancellationToken cancellationToken = default)

    Atomically bumps the L1 generation and the L2 principal epoch for `principalId`, immediately invalidating all cached snapshots for that user or service principal without `SCAN` operations.

    principalId: string
    The user or service principal identifier to invalidate.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A value task representing the invalidation operation.

  • methodInvalidatePrincipalsAsync
    public async ValueTask InvalidatePrincipalsAsync(IEnumerable<string> principalIds, CancellationToken cancellationToken = default)

    Atomically bumps the L1 generation and the L2 principal epochs for a batch of `principalIds` (for example, after a role mutation).

    principalIds: IEnumerable<string>
    The principal identifiers to invalidate.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A value task representing the batch invalidation operation.

  • methodInvalidateTenantAsync
    public async ValueTask InvalidateTenantAsync(string tenantId, CancellationToken cancellationToken = default)

    Atomically bumps the L1 generation and the L2 tenant epoch for `tenantId`, immediately invalidating all cached snapshots across the entire tenant in O(1) time.

    tenantId: string
    The tenant identifier to invalidate.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A value task representing the invalidation operation.

class

GenerationalPermissionCacheOptions

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class GenerationalPermissionCacheOptions

Configures TTL windows and cache key namespacing for `GenerationalPermissionCache`.

Miembros (4)

  • propertyEpochTtl
    public TimeSpan EpochTtl { get; set; }

    Gets or sets the retention TTL for L2 principal and tenant epoch keys. Defaults to 7 days.

  • propertyKeyPrefix
    public string KeyPrefix { get; set; }

    Gets or sets the distributed and in-memory cache key namespace prefix. Defaults to `"sec:perms"`.

  • propertyL1Ttl
    public TimeSpan L1Ttl { get; set; }

    Gets or sets the L1 in-memory (`Memory.IMemoryCache`) entry TTL. Defaults to 15 seconds.

  • propertyL2Ttl
    public TimeSpan L2Ttl { get; set; }

    Gets or sets the L2 distributed (`Distributed.IDistributedCache`) snapshot TTL. Defaults to 5 minutes.

class

SafeAuthorizationResultHandlerOptions

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class SafeAuthorizationResultHandlerOptions

Configures RFC 7807 ProblemDetails formatting and fail-closed `503 Service Unavailable` headers for `SafeMultiSchemeAuthorizationResultHandler`.

Miembros (3)

  • propertyCustomDetailResolver
    public Func<string, string?>? CustomDetailResolver { get; set; }

    Gets or sets an optional custom resolver mapping a machine-readable failure code to a human-readable detail message.

  • propertyProblemTypePrefix
    public string ProblemTypePrefix { get; set; }

    Gets or sets the RFC 7807 `type` URI prefix prepended to kebab-cased authorization failure codes. Defaults to `"urn:problem-type:security."`.

  • propertyRetryAfterSeconds
    public int RetryAfterSeconds { get; set; }

    Gets or sets the `Retry-After` header value (in seconds) returned on fail-closed `503 Service Unavailable` responses. Defaults to `5`.

class

SafeMultiSchemeAuthorizationResultHandler

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class SafeMultiSchemeAuthorizationResultHandler : IAuthorizationMiddlewareResultHandler
Implementa: IAuthorizationMiddlewareResultHandler

Provides a hardened, Native AOT-compatible `IAuthorizationMiddlewareResultHandler` that: - Enforces fail-closed HTTP `503 Service Unavailable` with `Retry-After` when revocation or authorization stores are unreachable. - Emits structured RFC 7807 `application/problem+json` `403 Forbidden` payloads with deterministic machine-readable failure codes. - Guards multi-scheme `ChallengeAsync` loops with `!context.Response.HasStarted` so secondary schemes never crash after a primary scheme writes a challenge body.

Miembros (2)

  • constructorSafeMultiSchemeAuthorizationResultHandler
    public SafeMultiSchemeAuthorizationResultHandler(IOptions<SafeAuthorizationResultHandlerOptions>? options = null)

    Initializes a new instance of the `SafeMultiSchemeAuthorizationResultHandler` class.

    options: IOptions<SafeAuthorizationResultHandlerOptions>?
    Optional configuration options.
  • methodHandleAsync
    public async Task HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)

    Inherits documentation from base type or interface.

    next: RequestDelegate
    context: HttpContext
    policy: AuthorizationPolicy
    authorizeResult: PolicyAuthorizationResult
class

SecurityPlaneAuthorizationHandler

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class SecurityPlaneAuthorizationHandler : AuthorizationHandler<SecurityPlaneRequirement>
Hereda de: AuthorizationHandler<SecurityPlaneRequirement>

Evaluates `SecurityPlaneRequirement` against verified principal claims (`plane`, `tenant_id`, `company_id`), preventing cross-plane lateral movement and rejecting contaminated `CONTROL` plane tokens.

Miembros (1)

  • constructorSecurityPlaneAuthorizationHandler
    public SecurityPlaneAuthorizationHandler(IHttpContextAccessor? httpContextAccessor = null)

    Initializes a new instance of the `SecurityPlaneAuthorizationHandler` class.

    httpContextAccessor: IHttpContextAccessor?
    Optional HTTP context accessor used to record failure reason codes.
record

SecurityPlaneRequirement

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed record SecurityPlaneRequirement(SecurityPlane ExpectedPlane, bool RequireCompanyScope) : IAuthorizationRequirement
Implementa: IAuthorizationRequirement

Authorization requirement enforcing strict isolation between `SecurityPlane.Control`, `SecurityPlane.Tenant`, and `SecurityPlane.Service` (`M2M`) execution planes.

Miembros (3)

  • constructorSecurityPlaneRequirement
    public SecurityPlaneRequirement(SecurityPlane ExpectedPlane, bool RequireCompanyScope = true)

    Initializes a new instance of SecurityPlaneRequirement.

    ExpectedPlane: SecurityPlane
    The required `SecurityPlane` for the endpoint.
    RequireCompanyScope: bool
    When `true` (default), `Tenant` and `Service` planes also require a non-empty `company_id` claim in addition to `tenant_id`.
  • propertyExpectedPlane
    public SecurityPlane ExpectedPlane { get; init; }

    The required `SecurityPlane` for the endpoint.

  • propertyRequireCompanyScope
    public bool RequireCompanyScope { get; init; }

    When `true` (default), `Tenant` and `Service` planes also require a non-empty `company_id` claim in addition to `tenant_id`.

class

TokenUseAuthorizationHandler

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class TokenUseAuthorizationHandler : AuthorizationHandler<TokenUseRequirement>
Hereda de: AuthorizationHandler<TokenUseRequirement>

Evaluates `TokenUseRequirement` to prevent pre-authentication or cross-purpose tokens from accessing operational endpoints and to enforce anti-impersonation boundaries.

Miembros (1)

  • constructorTokenUseAuthorizationHandler
    public TokenUseAuthorizationHandler(IHttpContextAccessor? httpContextAccessor = null)

    Initializes a new instance of the `TokenUseAuthorizationHandler` class.

    httpContextAccessor: IHttpContextAccessor?
    Optional HTTP context accessor used to record failure reason codes.
record

TokenUseRequirement

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed record TokenUseRequirement(string ExpectedScope, bool DisallowImpersonation) : IAuthorizationRequirement
Implementa: IAuthorizationRequirement

Authorization requirement enforcing that an authenticated token carries an exact `scope` or `token_use` claim (for example, `"access"`, `"pre_auth:mfa"`, `"pre_auth:onboarding"`, or `"m2m"`) and optionally prohibiting delegated support impersonation tokens.

Miembros (3)

  • constructorTokenUseRequirement
    public TokenUseRequirement(string ExpectedScope, bool DisallowImpersonation = false)

    Initializes a new instance of TokenUseRequirement.

    ExpectedScope: string
    The exact ordinal `scope` or `token_use` claim value required by the endpoint.
    DisallowImpersonation: bool
    When `true`, rejects tokens carrying active delegation/impersonation claims (`act` or `imp_sid`).
  • propertyDisallowImpersonation
    public bool DisallowImpersonation { get; init; }

    When `true`, rejects tokens carrying active delegation/impersonation claims (`act` or `imp_sid`).

  • propertyExpectedScope
    public string ExpectedScope { get; init; }

    The exact ordinal `scope` or `token_use` claim value required by the endpoint.

EricksonLopez.Security.AspNetCore.Configuration#

4
class

TmpfsSecretConfigurationExtensions

Ensamblado: EricksonLopez.Security.AspNetCore
public static class TmpfsSecretConfigurationExtensions

Provides extension methods for registering `TmpfsSecretConfigurationProvider` on `IConfigurationBuilder`.

Miembros (1)

  • methodAddTmpfsSecrets
    public static IConfigurationBuilder AddTmpfsSecrets(this IConfigurationBuilder builder, Action<TmpfsSecretOptions>? configure = null)

    Adds Docker/Kubernetes tmpfs RAM-backed secret files to `builder`.

    builder: this IConfigurationBuilder
    The configuration builder.
    configure: Action<TmpfsSecretOptions>?
    Optional callback to customize `TmpfsSecretOptions`.

    Retorna: The configured `IConfigurationBuilder`.

class

TmpfsSecretConfigurationProvider

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class TmpfsSecretConfigurationProvider : ConfigurationProvider, IDisposable
Hereda de: ConfigurationProviderImplementa: IDisposable

Loads and hot-reloads Docker/Kubernetes CSI RAM-backed tmpfs secret files into `IConfiguration`, mapping `__` in filenames to `:` configuration keys, ignoring hidden dotfiles/symlinks, trimming trailing newlines, and coalescing atomic symlink swaps via a debounced `Timer`.

Miembros (3)

  • constructorTmpfsSecretConfigurationProvider
    public TmpfsSecretConfigurationProvider(TmpfsSecretOptions options)

    Initializes a new instance of the `TmpfsSecretConfigurationProvider` class.

    options: TmpfsSecretOptions
    The tmpfs secret options.
  • methodDispose
    public void Dispose()

    Inherits documentation from base type or interface.

  • methodLoad
    public override void Load()

    Inherits documentation from base type or interface.

class

TmpfsSecretConfigurationSource

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class TmpfsSecretConfigurationSource : IConfigurationSource
Implementa: IConfigurationSource

Represents an `IConfigurationSource` backed by container tmpfs secret files.

Miembros (3)

  • constructorTmpfsSecretConfigurationSource
    public TmpfsSecretConfigurationSource(TmpfsSecretOptions options)

    Initializes a new instance of the `TmpfsSecretConfigurationSource` class.

    options: TmpfsSecretOptions
    The tmpfs secret options.
  • methodBuild
    public IConfigurationProvider Build(IConfigurationBuilder builder)

    Inherits documentation from base type or interface.

    builder: IConfigurationBuilder
  • propertyOptions
    public TmpfsSecretOptions Options { get; }

    Gets the configured `TmpfsSecretOptions`.

class

TmpfsSecretOptions

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class TmpfsSecretOptions

Configures Docker/Kubernetes RAM-backed tmpfs secret file loading and debounced hot-reloading for `TmpfsSecretConfigurationProvider`.

Miembros (3)

  • propertyDirectoryPath
    public string DirectoryPath { get; set; }

    Gets or sets the directory path containing secret files (for example, `"/run/secrets"`).

  • propertyReloadDebounce
    public TimeSpan ReloadDebounce { get; set; }

    Gets or sets the debounce window used to coalesce atomic multi-file Kubernetes CSI (`..data` symlink) rotations into a single reload. Defaults to 150 milliseconds.

  • propertyReloadOnChange
    public bool ReloadOnChange { get; set; }

    Gets or sets a value indicating whether file changes in `DirectoryPath` trigger automatic `IConfiguration` reloads. Defaults to `true`.

EricksonLopez.Security.AspNetCore.Context#

2
interface

IRequestSecurityContext

Ensamblado: EricksonLopez.Security.AspNetCore
public interface IRequestSecurityContext

Defines a scoped security context providing strongly-typed access to authenticated identity metadata, API keys, and authorization claims for the current HTTP request.

Miembros (7)

  • methodHasAllScopes
    bool HasAllScopes(params string[] scopes)

    Determines whether the authenticated principal or API key possesses all of the specified scopes.

    scopes: params string[]
    The scopes to check.

    Retorna: `true` if all scopes are granted; otherwise, `false`.

  • methodHasAnyScope
    bool HasAnyScope(params string[] scopes)

    Determines whether the authenticated principal or API key possesses any of the specified scopes.

    scopes: params string[]
    The scopes to check.

    Retorna: `true` if any scope is granted; otherwise, `false`.

  • methodHasScope
    bool HasScope(string scope)

    Determines whether the authenticated principal or API key possesses the specified scope.

    scope: string
    The scope to check.

    Retorna: `true` if granted; otherwise, `false`.

  • propertyActorId
    string? ActorId { get; }

    Gets the authenticated actor / user identifier, or `null` if unauthenticated.

  • propertyApiKey
    ApiKey? ApiKey { get; }

    Gets the authenticated `ApiKey` if the request was authenticated via API key.

  • propertyIsAuthenticated
    bool IsAuthenticated { get; }

    Gets a value indicating whether the current request is authenticated.

  • propertyPrincipal
    ClaimsPrincipal? Principal { get; }

    Gets the `ClaimsPrincipal` associated with the current HTTP context.

class

RequestSecurityContext

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class RequestSecurityContext : IRequestSecurityContext
Implementa: IRequestSecurityContext

Provides a scoped implementation of `IRequestSecurityContext` that resolves security properties from the active `IHttpContextAccessor`.

Miembros (8)

  • constructorRequestSecurityContext
    public RequestSecurityContext(IHttpContextAccessor httpContextAccessor)

    Initializes a new instance of the `RequestSecurityContext` class with the specified HTTP context accessor.

    httpContextAccessor: IHttpContextAccessor
    The accessor for retrieving the ambient HTTP context.

    Exceptions: ArgumentNullException: `httpContextAccessor` is `null`

  • methodHasAllScopes
    public bool HasAllScopes(params string[] scopes)

    Determines whether the authenticated principal or API key possesses all of the specified scopes.

    scopes: params string[]
    The scopes to check.

    Retorna: `true` if all scopes are granted; otherwise, `false`.

  • methodHasAnyScope
    public bool HasAnyScope(params string[] scopes)

    Determines whether the authenticated principal or API key possesses any of the specified scopes.

    scopes: params string[]
    The scopes to check.

    Retorna: `true` if any scope is granted; otherwise, `false`.

  • methodHasScope
    public bool HasScope(string scope)

    Determines whether the authenticated principal or API key possesses the specified scope.

    scope: string
    The scope to check.

    Retorna: `true` if granted; otherwise, `false`.

  • propertyActorId
    public string? ActorId { get; }

    Gets the unique identifier of the authenticated actor (user or subject) for the current request, if present.

  • propertyApiKey
    public ApiKey? ApiKey { get; }

    Gets the authenticated API key associated with the current HTTP request, if authenticated via API key.

  • propertyIsAuthenticated
    public bool IsAuthenticated { get; }

    Gets a value indicating whether the current request is authenticated.

  • propertyPrincipal
    public ClaimsPrincipal? Principal { get; }

    Gets the claims principal associated with the current HTTP request context.

EricksonLopez.Security.AspNetCore.DPoP#

10
enum

DPoPFailureReason

Ensamblado: EricksonLopez.Security.AspNetCore
public enum DPoPFailureReason

Categorizes specific RFC 9449 DPoP proof or token-binding validation failures.

Miembros (20)

  • fieldHttpMethodMismatch
    HttpMethodMismatch = 11

    The `htm` claim does not match the HTTP request method.

  • fieldHttpUriMismatch
    HttpUriMismatch = 12

    The `htu` claim is missing, relative/path-only, or does not match the canonical scheme, host, port, and path of the HTTP request.

  • fieldInvalidAccessTokenHash
    InvalidAccessTokenHash = 16

    The `ath` claim does not match `Base64Url(SHA-256(ASCII(rawAccessToken)))`.

  • fieldInvalidKeySize
    InvalidKeySize = 7

    The embedded RSA modulus bit length falls outside the configured `[MinimumRsaKeySizeBits..MaximumRsaKeySizeBits]` bounds.

  • fieldInvalidSignature
    InvalidSignature = 10

    The asymmetric cryptographic signature over the DPoP proof is invalid.

  • fieldInvalidTypHeader
    InvalidTypHeader = 3

    The JWS `typ` header is missing or does not equal `"dpop+jwt"`.

  • fieldKeyThumbprintMismatch
    KeyThumbprintMismatch = 9

    The RFC 7638 JWK SHA-256 thumbprint does not match the bound access token's `jkt` claim.

  • fieldMalformedProof
    MalformedProof = 2

    The DPoP proof JWT is syntactically malformed, oversized, or contains invalid JSON / Base64Url segments.

  • fieldMissingAccessToken
    MissingAccessToken = 14

    A DPoP-bound request presented no extractable raw access token for `ath` verification.

  • fieldMissingAccessTokenHash
    MissingAccessTokenHash = 15

    The DPoP proof is missing the mandatory `ath` access token hash claim.

  • fieldMissingOrDuplicateProofHeader
    MissingOrDuplicateProofHeader = 1

    The `DPoP` HTTP header is missing, empty, or duplicated.

  • fieldMissingOrInvalidJti
    MissingOrInvalidJti = 17

    The `jti` claim is missing, empty, or exceeds the maximum permitted length.

  • fieldMissingOrInvalidJwk
    MissingOrInvalidJwk = 5

    The JWS `jwk` header is missing or lacks required public key parameters.

  • fieldMissingTokenKeyBinding
    MissingTokenKeyBinding = 8

    The access token is missing a required `cnf.jkt` / `jkt` key-binding claim or has a malformed `cnf` claim.

  • fieldNone
    None = 0

    Validation succeeded with no failure.

  • fieldPrivateKeyMaterialInJwk
    PrivateKeyMaterialInJwk = 6

    The embedded `jwk` contains forbidden private or symmetric key material (`d`, `p`, `q`, `dp`, `dq`, `qi`, `oth`, `k`).

  • fieldProofExpiredOrFuture
    ProofExpiredOrFuture = 13

    The `iat` claim is missing, non-numeric, expired beyond `MaxProofAge`, or in the future beyond `ClockSkew`.

  • fieldReplayDetected
    ReplayDetected = 18

    The `jti` identifier has already been consumed or the replay store rejected acquisition fail-closed.

  • fieldUnsupportedAlgorithm
    UnsupportedAlgorithm = 4

    The JWS `alg` header is missing, `"none"`, symmetric (`HS*`), or otherwise unsupported.

  • fieldUntrustedHost
    UntrustedHost = 19

    The incoming HTTP `Host` header is missing or not permitted by `DPoPValidationOptions.AllowedHosts`.

class

DPoPProofValidationMiddleware

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class DPoPProofValidationMiddleware

ASP.NET Core middleware enforcing RFC 9449 Demonstrating Proof-of-Possession (DPoP) key-binding, `ath` access-token digest verification, full `htu` target URI validation, and atomic `jti` anti-replay on authenticated requests carrying DPoP-bound tokens.

Miembros (2)

  • constructorDPoPProofValidationMiddleware
    public DPoPProofValidationMiddleware(RequestDelegate next, IDPoPProofValidator validator, IOptions<DPoPValidationOptions>? options = null, ILogger<DPoPProofValidationMiddleware>? logger = null)

    Initializes a new instance of the `DPoPProofValidationMiddleware` class.

    next: RequestDelegate
    The next middleware delegate in the pipeline.
    validator: IDPoPProofValidator
    The DPoP proof validator.
    options: IOptions<DPoPValidationOptions>?
    Optional DPoP validation options.
    logger: ILogger<DPoPProofValidationMiddleware>?
    Optional structured logger.

    Exceptions: ArgumentNullException: `next` or `validator` is `null`.

  • methodInvokeAsync
    public async Task InvokeAsync(HttpContext context)

    Evaluates incoming HTTP requests and enforces RFC 9449 DPoP proof validation when applicable.

    context: HttpContext
    The current `HttpContext`.

    Retorna: A task representing the asynchronous middleware execution.

record

DPoPProofValidationRequest

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed record DPoPProofValidationRequest(string ProofJwt, string HttpMethod, string HttpUri, string? ExpectedKeyThumbprint, string? RawAccessToken, bool RequireKeyBinding, bool RequireAccessTokenHash)

Encapsulates the inputs required to validate an RFC 9449 DPoP proof JWT against an HTTP request and bound access token.

Miembros (8)

  • constructorDPoPProofValidationRequest
    public DPoPProofValidationRequest(string ProofJwt, string HttpMethod, string HttpUri, string? ExpectedKeyThumbprint, string? RawAccessToken = null, bool RequireKeyBinding = true, bool RequireAccessTokenHash = true)

    Initializes a new instance of DPoPProofValidationRequest.

    ProofJwt: string
    The compact serialized DPoP proof JWT extracted from the `DPoP` HTTP request header.
    HttpMethod: string
    The HTTP request method (for example, `"POST"` or `"GET"`).
    HttpUri: string
    The full canonical HTTP target URI (`scheme://host[:port]/path`; query and fragment are stripped per RFC 9449 §4.3).
    ExpectedKeyThumbprint: string?
    The expected RFC 7638 JWK SHA-256 thumbprint (`cnf.jkt` / `jkt`) bound to the access token, when validating a resource request.
    RawAccessToken: string?
    The raw ASCII access token presented on the request, used to verify the `ath` claim when `RequireAccessTokenHash` is `true`.
    RequireKeyBinding: bool
    When `true` (default for resource servers), `ExpectedKeyThumbprint` is mandatory and verified in constant time before asymmetric key construction.
    RequireAccessTokenHash: bool
    When `true` (default for resource servers), `RawAccessToken` and the proof's `ath` claim are mandatory and verified in constant time.
  • propertyExpectedKeyThumbprint
    public string? ExpectedKeyThumbprint { get; init; }

    The expected RFC 7638 JWK SHA-256 thumbprint (`cnf.jkt` / `jkt`) bound to the access token, when validating a resource request.

  • propertyHttpMethod
    public string HttpMethod { get; init; }

    The HTTP request method (for example, `"POST"` or `"GET"`).

  • propertyHttpUri
    public string HttpUri { get; init; }

    The full canonical HTTP target URI (`scheme://host[:port]/path`; query and fragment are stripped per RFC 9449 §4.3).

  • propertyProofJwt
    public string ProofJwt { get; init; }

    The compact serialized DPoP proof JWT extracted from the `DPoP` HTTP request header.

  • propertyRawAccessToken
    public string? RawAccessToken { get; init; }

    The raw ASCII access token presented on the request, used to verify the `ath` claim when `RequireAccessTokenHash` is `true`.

  • propertyRequireAccessTokenHash
    public bool RequireAccessTokenHash { get; init; }

    When `true` (default for resource servers), `RawAccessToken` and the proof's `ath` claim are mandatory and verified in constant time.

  • propertyRequireKeyBinding
    public bool RequireKeyBinding { get; init; }

    When `true` (default for resource servers), `ExpectedKeyThumbprint` is mandatory and verified in constant time before asymmetric key construction.

class

DPoPProofValidationResult

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class DPoPProofValidationResult

Represents the outcome of validating an RFC 9449 DPoP proof JWT.

Miembros (10)

  • methodFailure
    public static DPoPProofValidationResult Failure(DPoPFailureReason reason, string errorCode, string errorDescription)

    Creates a failed `DPoPProofValidationResult`.

    reason: DPoPFailureReason
    The structured failure reason.
    errorCode: string
    The machine-readable error identifier.
    errorDescription: string
    The human-readable RFC 9449 error description.

    Retorna: A failed `DPoPProofValidationResult`.

  • methodSuccess
    public static DPoPProofValidationResult Success(string jti, string jwkThumbprint, DateTimeOffset issuedAtUtc)

    Creates a successful `DPoPProofValidationResult`.

    jti: string
    The validated proof `jti`.
    jwkThumbprint: string
    The validated RFC 7638 JWK SHA-256 thumbprint.
    issuedAtUtc: DateTimeOffset
    The validated `iat` timestamp.

    Retorna: A valid `DPoPProofValidationResult`.

  • propertyErrorCode
    public string? ErrorCode { get; }

    Gets the deterministic machine-readable error identifier when `IsValid` is `false`.

  • propertyErrorDescription
    public string? ErrorDescription { get; }

    Gets the RFC 9449 `error_description` diagnostic summary when `IsValid` is `false`.

  • propertyFailureReason
    public DPoPFailureReason FailureReason { get; }

    Gets the structured failure reason when `IsValid` is `false`, or `DPoPFailureReason.None` on success.

  • propertyIsValid
    public bool IsValid { get; }

    Gets a value indicating whether the DPoP proof passed all structural, cryptographic, binding, freshness, and anti-replay checks.

  • propertyIssuedAtUtc
    public DateTimeOffset? IssuedAtUtc { get; }

    Gets the validated `iat` timestamp when `IsValid` is `true`.

  • propertyJti
    public string? Jti { get; }

    Gets the validated `jti` proof identifier when `IsValid` is `true`.

  • propertyJwkThumbprint
    public string? JwkThumbprint { get; }

    Gets the validated RFC 7638 JWK SHA-256 thumbprint (`jkt`) when `IsValid` is `true`.

  • propertyWwwAuthenticateError
    public string WwwAuthenticateError { get; }

    Gets the RFC 9449 §7.1 `WWW-Authenticate: DPoP error="..."` token corresponding to `FailureReason`.

class

DPoPProofValidator

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class DPoPProofValidator : IDPoPProofValidator
Implementa: IDPoPProofValidator

Provides a hardened, zero-reflection, Native AOT-compatible RFC 9449 DPoP proof validator. Verifies the RFC 7638 JWK SHA-256 thumbprint (`jkt`) in constant time and RSA modulus bit bounds prior to instantiating `RSA` or `ECDsa` primitives to defeat asymmetric CPU DoS attacks.

Miembros (4)

  • constructorDPoPProofValidator
    public DPoPProofValidator(IDPoPReplayStore replayStore, IOptions<DPoPValidationOptions>? options = null, TimeProvider? timeProvider = null)

    Initializes a new instance of the `DPoPProofValidator` class.

    replayStore: IDPoPReplayStore
    The atomic `jti` anti-replay store.
    options: IOptions<DPoPValidationOptions>?
    Optional DPoP validation options.
    timeProvider: TimeProvider?
    Optional time provider (defaults to `TimeProvider.System`).

    Exceptions: ArgumentNullException: `replayStore` is `null`.

  • methodComputeAccessTokenHash
    public static string ComputeAccessTokenHash(string rawAccessToken)

    Computes the RFC 9449 §4.2 `ath` claim value (`Base64Url(SHA-256(ASCII(rawAccessToken)))`) for an ASCII access token.

    rawAccessToken: string
    The raw ASCII access token string.

    Retorna: The Base64Url-encoded SHA-256 access token digest.

    Exceptions: ArgumentException: `rawAccessToken` is null, whitespace, or contains non-ASCII characters.

  • methodTryComputeJwkThumbprint
    public static bool TryComputeJwkThumbprint(ReadOnlySpan<char> jwkJson, out string thumbprint)

    Computes the canonical RFC 7638 SHA-256 thumbprint (`jkt`) of a public RSA or EC JWK JSON object, returning `false` if malformed or if any private/symmetric parameter is present.

    jwkJson: ReadOnlySpan<char>
    The UTF-16 JSON representation of the JWK.
    thumbprint: out string
    When successful, receives the Base64Url-encoded SHA-256 JWK thumbprint.

    Retorna: `true` if the JWK is a valid public RSA or EC JWK; otherwise, `false`.

  • methodValidateAsync
    public async ValueTask<DPoPProofValidationResult> ValidateAsync(DPoPProofValidationRequest request, CancellationToken cancellationToken = default)

    Validates an RFC 9449 DPoP proof JWT, enforcing header constraints, private-key JWK rejection, pre-verification RFC 7638 `jkt` constant-time binding, asymmetric signature verification, `htm` and full `htu` URI matching, `iat` freshness, `ath` access-token binding, and atomic `jti` anti-replay.

    request: DPoPProofValidationRequest
    The DPoP proof validation request parameters.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: The `DPoPProofValidationResult` describing the validation outcome.

class

DPoPValidationOptions

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class DPoPValidationOptions

Configures RFC 9449 Demonstrating Proof-of-Possession (DPoP) cryptographic validation, URI canonicalization, freshness windows, and replay defense options.

Miembros (15)

  • propertyAllowQueryStringAccessToken
    public bool AllowQueryStringAccessToken { get; set; }

    Gets or sets a value indicating whether raw access tokens may be extracted from a query-string parameter (for example, browser WebSocket / SignalR upgrade handshakes) when no `Authorization` header is present. Defaults to `false`.

  • propertyAllowedHosts
    public ISet<string> AllowedHosts { get; }

    Gets an optional allowlist of permitted HTTP `Host` authorities (`host` or `host:port`). When non-empty, requests whose `Host` header is not in `AllowedHosts` are rejected fail-closed with HTTP 401.

  • propertyCanonicalHost
    public string? CanonicalHost { get; set; }

    Gets or sets an optional canonical authority (`host[:port]`) override used when reconstructing the expected `htu` target URI. When `null` or empty, `HttpRequest.Host` is used.

  • propertyCanonicalScheme
    public string? CanonicalScheme { get; set; }

    Gets or sets an optional canonical URI scheme override (for example, `"https"`) used when reconstructing the expected `htu` target URI. When `null` or empty, `HttpRequest.Scheme` is used.

  • propertyClockSkew
    public TimeSpan ClockSkew { get; set; }

    Gets or sets the tolerated clock skew for `iat` timestamps slightly in the future or past. Defaults to 30 seconds.

  • propertyMaxProofAge
    public TimeSpan MaxProofAge { get; set; }

    Gets or sets the maximum permitted age of a DPoP proof `iat` timestamp. Defaults to 300 seconds (5 minutes).

  • propertyMaximumJtiLength
    public int MaximumJtiLength { get; set; }

    Gets or sets the maximum permitted length in characters of a DPoP `jti` claim. Defaults to 256 characters.

  • propertyMaximumProofTokenLength
    public int MaximumProofTokenLength { get; set; }

    Gets or sets the maximum permitted length in characters of a compact DPoP proof JWT header value. Defaults to 16,384 characters.

  • propertyMaximumRsaKeySizeBits
    public int MaximumRsaKeySizeBits { get; set; }

    Gets or sets the maximum permitted RSA modulus size in bits for embedded DPoP public keys to prevent asymmetric CPU DoS. Defaults to 4096 bits.

  • propertyMinimumRsaKeySizeBits
    public int MinimumRsaKeySizeBits { get; set; }

    Gets or sets the minimum permitted RSA modulus size in bits for embedded DPoP public keys. Defaults to 2048 bits.

  • propertyProofHeaderName
    public string ProofHeaderName { get; set; }

    Gets or sets the HTTP request header name carrying the DPoP proof JWT. Defaults to `"DPoP"`.

  • propertyQueryStringTokenAllowedPathPrefixes
    public ISet<string> QueryStringTokenAllowedPathPrefixes { get; }

    Gets an optional allowlist of request path prefixes (for example, `"/hubs"`) where query-string token extraction is permitted when `AllowQueryStringAccessToken` is `true`. When empty, all paths are eligible if `AllowQueryStringAccessToken` is enabled.

  • propertyQueryStringTokenParameterName
    public string QueryStringTokenParameterName { get; set; }

    Gets or sets the query-string parameter name inspected when `AllowQueryStringAccessToken` is `true`. Defaults to `"access_token"`.

  • propertyReplayCacheTtl
    public TimeSpan ReplayCacheTtl { get; set; }

    Gets or sets the time-to-live duration for tracked `jti` identifiers in `IDPoPReplayStore`. Defaults to 330 seconds (`MaxProofAge + ClockSkew`).

  • propertyRequireDPoPForAllAuthenticatedRequests
    public bool RequireDPoPForAllAuthenticatedRequests { get; set; }

    Gets or sets a value indicating whether all authenticated requests must be DPoP-bound, rejecting plain Bearer tokens lacking `cnf.jkt`. Defaults to `false` (enforces DPoP on any token carrying `cnf.jkt`/`jkt` or using the `DPoP` authorization scheme).

class

DistributedCacheDPoPReplayStore

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class DistributedCacheDPoPReplayStore : IDPoPReplayStore
Implementa: IDPoPReplayStore

Provides a fail-closed distributed `IDPoPReplayStore` backed by `IDistributedCache` with a bounded in-process L1 atomic barrier and fixed-stripe concurrency gates.

Miembros (2)

  • constructorDistributedCacheDPoPReplayStore
    public DistributedCacheDPoPReplayStore(IDistributedCache cache, TimeProvider? timeProvider = null, ILogger<DistributedCacheDPoPReplayStore>? logger = null, string keyPrefix = DefaultKeyPrefix, int maxLocalBarrierEntries = 100_000)

    Initializes a new instance of the `DistributedCacheDPoPReplayStore` class.

    cache: IDistributedCache
    The distributed cache backing cross-node JTI anti-replay tracking.
    timeProvider: TimeProvider?
    Optional time provider (defaults to `TimeProvider.System`).
    logger: ILogger<DistributedCacheDPoPReplayStore>?
    Optional structured logger.
    keyPrefix: string
    Cache key prefix (defaults to `"sec:dpop:jti:"`).
    maxLocalBarrierEntries: int
    Maximum entries in the in-process L1 anti-replay barrier (defaults to 100,000).

    Exceptions: ArgumentNullException: `cache` is `null`.; ArgumentOutOfRangeException: `maxLocalBarrierEntries` is less than or equal to zero.

  • methodTryAcquireJtiAsync
    public async ValueTask<bool> TryAcquireJtiAsync(string jti, TimeSpan ttl, CancellationToken cancellationToken = default)

    Atomically records `jti` with the specified `ttl` if it has not already been seen within its active validity window.

    jti: string
    The unique DPoP proof token identifier.
    ttl: TimeSpan
    The time-to-live duration for which the `jti` must remain blocked from replay.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: `true` if `jti` was newly acquired and is not a replay; `false` if `jti` was already seen, invalid, or the store is saturated/unavailable (fail-closed).

interface

IDPoPProofValidator

Ensamblado: EricksonLopez.Security.AspNetCore
public interface IDPoPProofValidator

Defines a Native AOT-safe, zero-reflection validator for RFC 9449 Demonstrating Proof-of-Possession (DPoP) proofs.

Miembros (1)

  • methodValidateAsync
    ValueTask<DPoPProofValidationResult> ValidateAsync(DPoPProofValidationRequest request, CancellationToken cancellationToken = default)

    Validates an RFC 9449 DPoP proof JWT, enforcing header constraints, private-key JWK rejection, pre-verification RFC 7638 `jkt` constant-time binding, asymmetric signature verification, `htm` and full `htu` URI matching, `iat` freshness, `ath` access-token binding, and atomic `jti` anti-replay.

    request: DPoPProofValidationRequest
    The DPoP proof validation request parameters.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: The `DPoPProofValidationResult` describing the validation outcome.

interface

IDPoPReplayStore

Ensamblado: EricksonLopez.Security.AspNetCore
public interface IDPoPReplayStore

Defines an atomic anti-replay store for RFC 9449 DPoP proof `jti` identifiers.

Miembros (1)

  • methodTryAcquireJtiAsync
    ValueTask<bool> TryAcquireJtiAsync(string jti, TimeSpan ttl, CancellationToken cancellationToken = default)

    Atomically records `jti` with the specified `ttl` if it has not already been seen within its active validity window.

    jti: string
    The unique DPoP proof token identifier.
    ttl: TimeSpan
    The time-to-live duration for which the `jti` must remain blocked from replay.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: `true` if `jti` was newly acquired and is not a replay; `false` if `jti` was already seen, invalid, or the store is saturated/unavailable (fail-closed).

class

InMemoryDPoPReplayStore

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class InMemoryDPoPReplayStore : IDPoPReplayStore
Implementa: IDPoPReplayStore

Provides a bounded, thread-safe, `TimeProvider`-aware in-memory `IDPoPReplayStore` that sweeps expired entries on capacity pressure without ever evicting unexpired entries silently, failing closed when genuinely saturated.

Miembros (4)

  • constructorInMemoryDPoPReplayStore
    public InMemoryDPoPReplayStore(int maxEntries = 100_000, TimeProvider? timeProvider = null)

    Initializes a new instance of the `InMemoryDPoPReplayStore` class.

    maxEntries: int
    The hard upper bound on active unexpired JTI entries (defaults to 100,000).
    timeProvider: TimeProvider?
    Optional time provider (defaults to `TimeProvider.System`).

    Exceptions: ArgumentOutOfRangeException: `maxEntries` is less than or equal to zero.

  • methodTryAcquireJtiAsync
    public ValueTask<bool> TryAcquireJtiAsync(string jti, TimeSpan ttl, CancellationToken cancellationToken = default)

    Atomically records `jti` with the specified `ttl` if it has not already been seen within its active validity window.

    jti: string
    The unique DPoP proof token identifier.
    ttl: TimeSpan
    The time-to-live duration for which the `jti` must remain blocked from replay.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: `true` if `jti` was newly acquired and is not a replay; `false` if `jti` was already seen, invalid, or the store is saturated/unavailable (fail-closed).

  • propertyCount
    public int Count { get; }

    Gets the current count of tracked JTI entries in memory.

  • propertyMaxEntries
    public int MaxEntries { get; }

    Gets the configured hard upper bound on stored JTI entries.

EricksonLopez.Security.AspNetCore.Headers#

2
class

SecurityHeadersMiddleware

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class SecurityHeadersMiddleware

Middleware that enforces enterprise security response headers on all outgoing HTTP responses to mitigate clickjacking, MIME-sniffing, XSS, and transport downgrade attacks.

Miembros (2)

  • constructorSecurityHeadersMiddleware
    public SecurityHeadersMiddleware(RequestDelegate next, IOptions<SecurityHeadersOptions> options)

    Initializes a new instance of the `SecurityHeadersMiddleware` class.

    next: RequestDelegate
    The next middleware in the pipeline.
    options: IOptions<SecurityHeadersOptions>
    Security headers configuration options.

    Exceptions: ArgumentNullException: `next` is `null`

  • methodInvokeAsync
    public async Task InvokeAsync(HttpContext context)

    Injects the configured security headers into the response headers collection.

    context: HttpContext
    The HTTP context.

    Retorna: A task representing the asynchronous pipeline operation.

    Exceptions: ArgumentNullException: `context` is `null`

class

SecurityHeadersOptions

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class SecurityHeadersOptions

Specifies configuration options for injecting enterprise security response headers.

Miembros (10)

  • propertyContentSecurityPolicy
    public string ContentSecurityPolicy { get; set; }

    Gets or sets the Content-Security-Policy (CSP) header value. Default: `default-src 'self'; frame-ancestors 'none'; object-src 'none'; base-uri 'self';`.

  • propertyNoStorePathPrefixes
    public IList<string> NoStorePathPrefixes { get; }

    Gets request path prefixes (such as `"/api/v1/auth"`) that automatically receive `Cache-Control: no-store, no-cache, max-age=0` and `Pragma: no-cache`.

  • propertyPermissionsPolicy
    public string PermissionsPolicy { get; set; }

    Gets or sets the Permissions-Policy header value. Default: `accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()`.

  • propertyReferrerPolicy
    public string ReferrerPolicy { get; set; }

    Gets or sets the Referrer-Policy header value. Default: `strict-origin-when-cross-origin`.

  • propertyRemoveServerFingerprintingHeaders
    public bool RemoveServerFingerprintingHeaders { get; set; }

    Gets or sets a value indicating whether server technology fingerprinting headers (`Server` and `X-Powered-By`) are stripped from outgoing responses. Default: `true`.

  • propertyStrictTransportSecurity
    public string StrictTransportSecurity { get; set; }

    Gets or sets the HTTP Strict Transport Security (HSTS) header value. Default: `max-age=31536000; includeSubDomains; preload`.

  • propertyTrustXForwardedProtoForHsts
    public bool TrustXForwardedProtoForHsts { get; set; }

    Gets or sets a value indicating whether `X-Forwarded-Proto: https` is trusted when evaluating HSTS header injection behind a TLS-terminating reverse proxy. Default: `false`.

  • propertyXContentTypeOptions
    public string XContentTypeOptions { get; set; }

    Gets or sets the X-Content-Type-Options header value. Default: `nosniff`.

  • propertyXFrameOptions
    public string XFrameOptions { get; set; }

    Gets or sets the X-Frame-Options header value. Default: `DENY`.

  • propertyXPermittedCrossDomainPolicies
    public string XPermittedCrossDomainPolicies { get; set; }

    Gets or sets the X-Permitted-Cross-Domain-Policies header value. Default: `none`.

EricksonLopez.Security.AspNetCore.Hosting#

2
class

KestrelDualPortExtensions

Ensamblado: EricksonLopez.Security.AspNetCore
public static class KestrelDualPortExtensions

Provides extension methods for hardening Kestrel with `AddServerHeader = false`, strict 1 MiB default body ceilings, and optional dual-port public REST vs. internal S2S/gRPC TCP listener isolation.

Miembros (2)

  • methodApplyHardening
    public static void ApplyHardening(KestrelServerOptions kestrel, KestrelPerimeterOptions options)

    Applies Kestrel perimeter hardening directly onto a `KestrelServerOptions` instance.

    kestrel: KestrelServerOptions
    The Kestrel server options.
    options: KestrelPerimeterOptions
    The perimeter configuration options.
  • methodUseHardenedDualPortKestrel
    public static IWebHostBuilder UseHardenedDualPortKestrel(this IWebHostBuilder webHostBuilder, IConfiguration configuration, Action<KestrelPerimeterOptions>? configure = null)

    Applies Kestrel perimeter hardening and optional dual-port listener separation bound from `configuration`.

    webHostBuilder: this IWebHostBuilder
    The web host builder to configure.
    configuration: IConfiguration
    The application configuration root.
    configure: Action<KestrelPerimeterOptions>?
    Optional delegate overriding `KestrelPerimeterOptions`.

    Retorna: The configured `IWebHostBuilder`.

class

KestrelPerimeterOptions

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class KestrelPerimeterOptions

Configures hardened Kestrel dual-port network listener separation, server-header suppression, and default request body size limits.

Miembros (8)

  • propertyCertificatePassword
    public string? CertificatePassword { get; set; }

    Gets or sets an optional password for `CertificatePath`.

  • propertyCertificatePath
    public string? CertificatePath { get; set; }

    Gets or sets an optional PKCS#12 (`.pfx`) TLS certificate path used when `Enabled` is `true`.

  • propertyDefaultMaxRequestBodySize
    public long DefaultMaxRequestBodySize { get; set; }

    Gets or sets the default maximum request body size in bytes enforced at the Kestrel transport layer. Defaults to 1 MiB (`1,048,576` bytes). Individual upload endpoints may opt in to higher limits via `[RequestSizeLimit]`.

  • propertyEnabled
    public bool Enabled { get; set; }

    Gets or sets a value indicating whether explicit dual-port listener binding (`PublicPort` and `InternalS2SPort`) is active. Transport hardening (`AddServerHeader = false` and `DefaultMaxRequestBodySize`) always applies regardless of this flag.

  • propertyInternalS2SPort
    public int InternalS2SPort { get; set; }

    Gets or sets the internal service-to-service / gRPC TCP port (HTTP/2). Defaults to `9445`.

  • propertyPublicPort
    public int PublicPort { get; set; }

    Gets or sets the external public REST API TCP port (HTTP/1.1 + HTTP/2). Defaults to `8445`.

  • propertyRequireClientCertificateOnInternalPort
    public bool RequireClientCertificateOnInternalPort { get; set; }

    Gets or sets a value indicating whether mutual TLS client certificates are required on `InternalS2SPort`.

  • fieldSectionName
    public const string SectionName

    Default configuration section name (`"KestrelDualPort"`).

EricksonLopez.Security.AspNetCore.Identity#

2
class

IdentityPasswordHasherBridge

Ensamblado: EricksonLopez.Security.AspNetCore
public static class IdentityPasswordHasherBridge

Provides dependency injection registration extensions for `IdentityPasswordHasherBridge<TUser>`.

Miembros (1)

  • methodAddEricksonLopezIdentityPasswordHasher<TUser>
    public static Microsoft.Extensions.DependencyInjection.IServiceCollection AddEricksonLopezIdentityPasswordHasher<TUser>(this Microsoft.Extensions.DependencyInjection.IServiceCollection services) where TUser : class

    Registers `IdentityPasswordHasherBridge<TUser>` as the `IPasswordHasher<TUser>` implementation.

    services: this Microsoft.Extensions.DependencyInjection.IServiceCollection
    The service collection.

    Retorna: The service collection for chaining.

    Type parameters: TUser: The user entity type.

class

IdentityPasswordHasherBridge<TUser>

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class IdentityPasswordHasherBridge<TUser> : IPasswordHasher<TUser> where TUser : class
Implementa: IPasswordHasher<TUser>

Bridges ASP.NET Core Identity's `IPasswordHasher<TUser>` to the canonical `ElPasswordHasher` from EricksonLopez.Security, enabling zero-downtime, transparent password migration.

Notas:

Type parameters: TUser: The user entity type.

Miembros (3)

  • constructorIdentityPasswordHasherBridge
    public IdentityPasswordHasherBridge(ElPasswordHasher hasher)

    Initializes a new instance of the `IdentityPasswordHasherBridge<TUser>` class.

    hasher: ElPasswordHasher
    The underlying EricksonLopez.Security password hasher.

    Exceptions: ArgumentNullException: `hasher` is `null`

  • methodHashPassword
    public string HashPassword(TUser user, string password)

    Inherits documentation from base type or interface.

    user: TUser
    password: string
  • methodVerifyHashedPassword
    public PasswordVerificationResult VerifyHashedPassword(TUser user, string hashedPassword, string providedPassword)

    Inherits documentation from base type or interface.

    user: TUser
    hashedPassword: string
    providedPassword: string

EricksonLopez.Security.AspNetCore.Revocation#

1
class

DistributedCacheFailClosedTokenDenyList

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class DistributedCacheFailClosedTokenDenyList : ITokenDenyList
Implementa: ITokenDenyList

Provides a fail-closed `ITokenDenyList` backed by `IDistributedCache` (such as Redis). Empty identifiers are treated as denied (`true`), and any backing-store exception raises `TokenRevocationStoreUnavailableException` so callers return HTTP `503 Service Unavailable` rather than failing open.

Miembros (5)

  • constructorDistributedCacheFailClosedTokenDenyList
    public DistributedCacheFailClosedTokenDenyList(IDistributedCache cache, ILogger<DistributedCacheFailClosedTokenDenyList>? logger = null, string tokenKeyPrefix = DefaultTokenKeyPrefix, string principalKeyPrefix = DefaultPrincipalKeyPrefix)

    Initializes a new instance of the `DistributedCacheFailClosedTokenDenyList` class.

    cache: IDistributedCache
    The distributed cache backing the revocation list.
    logger: ILogger<DistributedCacheFailClosedTokenDenyList>?
    Optional structured logger.
    tokenKeyPrefix: string
    Optional key prefix for revoked token JTIs (defaults to `"token_deny:"`).
    principalKeyPrefix: string
    Optional key prefix for globally revoked principals (defaults to `"user_deny:"`).

    Exceptions: ArgumentNullException: `cache` is `null`.

  • methodDenyPrincipalAsync
    public async Task DenyPrincipalAsync(string principalId, TimeSpan ttl, CancellationToken cancellationToken = default)

    Globally revokes all active tokens for a principal identifier over the specified `ttl` window.

    principalId: string
    The unique user or service principal identifier.
    ttl: TimeSpan
    The revocation window duration (must cover maximum token lifetime).
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A task representing the asynchronous principal revocation write.

    Exceptions: TokenRevocationStoreUnavailableException: The underlying revocation store is unreachable.

  • methodDenyTokenAsync
    public async Task DenyTokenAsync(string jti, TimeSpan ttl, CancellationToken cancellationToken = default)

    Adds a specific token identifier (`jti`) to the revocation deny-list for its remaining time-to-live.

    jti: string
    The unique token identifier (`jti`).
    ttl: TimeSpan
    The time-to-live duration for the revocation entry.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A task representing the asynchronous revocation write.

    Exceptions: TokenRevocationStoreUnavailableException: The underlying revocation store is unreachable.

  • methodIsPrincipalDeniedAsync
    public async Task<bool> IsPrincipalDeniedAsync(string principalId, CancellationToken cancellationToken = default)

    Determines whether a principal identifier is currently subject to global token revocation. Implementations must enforce fail-closed semantics: empty `principalId` returns `true`, and store connectivity failures throw `TokenRevocationStoreUnavailableException`.

    principalId: string
    The unique user or service principal identifier.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: `true` if the principal is denied or empty; otherwise, `false`.

    Exceptions: TokenRevocationStoreUnavailableException: The underlying revocation store is unreachable.

  • methodIsTokenDeniedAsync
    public async Task<bool> IsTokenDeniedAsync(string jti, CancellationToken cancellationToken = default)

    Determines whether a specific token identifier (`jti`) has been revoked. Implementations must enforce fail-closed semantics: empty `jti` returns `true`, and store connectivity failures throw `TokenRevocationStoreUnavailableException`.

    jti: string
    The unique token identifier (`jti`).
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: `true` if the token is denied or missing a valid identifier; otherwise, `false`.

    Exceptions: TokenRevocationStoreUnavailableException: The underlying revocation store is unreachable.

EricksonLopez.Security.AspNetCore.Serialization#

1
class

NullByteSanitizingStringJsonConverter

Ensamblado: EricksonLopez.Security.AspNetCore
public sealed class NullByteSanitizingStringJsonConverter : JsonConverter<string>
Hereda de: JsonConverter<string>

Strips embedded NUL bytes (`\u0000` / `0x00`) from incoming JSON strings at the HTTP deserialization perimeter with a zero-allocation fast path for clean strings, preventing PostgreSQL UTF-8 `22021` encoding crashes.

Miembros (2)

  • methodRead
    public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)

    Inherits documentation from base type or interface.

    reader: ref Utf8JsonReader
    typeToConvert: Type
    options: JsonSerializerOptions
  • methodWrite
    public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)

    Inherits documentation from base type or interface.

    writer: Utf8JsonWriter
    value: string
    options: JsonSerializerOptions

EricksonLopez.Security.Aws#

3
class

AwsKmsKeyStore

Ensamblado: EricksonLopez.Security.Aws
public sealed class AwsKmsKeyStore : IKeyStore, IDisposable
Implementa: IDisposable, IKeyStore

Provides an `IKeyStore` adapter backed by AWS Key Management Service (KMS) and Secrets Manager.

Notas:

Connects directly to AWS Secrets Manager with KMS CMK encryption to persist cryptographic keys and their associated lifecycle metadata durably.

Miembros (8)

  • constructorAwsKmsKeyStore
    public AwsKmsKeyStore(IAmazonKeyManagementService kmsClient, IAmazonSecretsManager secretsManagerClient, IOptions<AwsSecurityOptions> options, ILogger<AwsKmsKeyStore>? logger = null)

    Initializes a new instance of the `AwsKmsKeyStore` class using pre-configured SDK clients.

    kmsClient: IAmazonKeyManagementService
    The AWS KMS client.
    secretsManagerClient: IAmazonSecretsManager
    The AWS Secrets Manager client.
    options: IOptions<AwsSecurityOptions>
    The AWS security options.
    logger: ILogger<AwsKmsKeyStore>?
    Optional logger for diagnostics.
  • constructorAwsKmsKeyStore
    public AwsKmsKeyStore(IOptions<AwsSecurityOptions> options)

    Initializes a new instance of the `AwsKmsKeyStore` class with default null logger.

    options: IOptions<AwsSecurityOptions>
    The AWS security options.
  • constructorAwsKmsKeyStore
    public AwsKmsKeyStore(IOptions<AwsSecurityOptions> options, ILogger<AwsKmsKeyStore> logger)

    Initializes a new instance of the `AwsKmsKeyStore` class.

    options: IOptions<AwsSecurityOptions>
    The AWS security options.
    logger: ILogger<AwsKmsKeyStore>
    The logger for diagnostics and operational warnings.

    Exceptions: ArgumentNullException: `options` or `logger` is `null`; InvalidOperationException: Options are missing required KMS key ID or credentials

  • methodDispose
    public void Dispose()

    Releases the resources used by this instance.

  • methodGetKeyAsync
    public async ValueTask<Result<CryptographicKey>> GetKeyAsync(KeyIdentifier keyId, KeyVersion version, CancellationToken cancellationToken = default)

    Retrieves a cryptographic key by identifier and version.

    keyId: KeyIdentifier
    The key identifier.
    version: KeyVersion
    The key version.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the `CryptographicKey`.

  • methodListMetadataAsync
    public async ValueTask<Result<IReadOnlyList<KeyMetadata>>> ListMetadataAsync(KeyPurpose? purpose = null, CancellationToken cancellationToken = default)

    Retrieves all key metadata stored in the repository.

    purpose: KeyPurpose?
    Optional purpose filter.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a result with a list of key metadata records.

  • methodSaveKeyAsync
    public async ValueTask<Result> SaveKeyAsync(CryptographicKey key, CancellationToken cancellationToken = default)

    Persists a new cryptographic key into the key store.

    key: CryptographicKey
    The cryptographic key to save.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating success or failure.

  • methodUpdateStatusAsync
    public async ValueTask<Result> UpdateStatusAsync(KeyIdentifier keyId, KeyVersion version, KeyStatus newStatus, CancellationToken cancellationToken = default)

    Updates the lifecycle status of a specific key.

    keyId: KeyIdentifier
    The key identifier.
    version: KeyVersion
    The key version.
    newStatus: KeyStatus
    The new lifecycle status.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating the outcome.

class

AwsSecretsManagerSecretStore

Ensamblado: EricksonLopez.Security.Aws
public sealed class AwsSecretsManagerSecretStore : ISecretStore, IDisposable
Implementa: IDisposable, ISecretStore

Provides an `ISecretStore` adapter backed by AWS Secrets Manager.

Notas:

Connects directly to AWS Secrets Manager using `IAmazonSecretsManager`.

Miembros (6)

  • constructorAwsSecretsManagerSecretStore
    public AwsSecretsManagerSecretStore(IAmazonSecretsManager secretsManagerClient, IOptions<AwsSecurityOptions>? options = null, ILogger<AwsSecretsManagerSecretStore>? logger = null)

    Initializes a new instance of the `AwsSecretsManagerSecretStore` class using a pre-configured client.

    secretsManagerClient: IAmazonSecretsManager
    The AWS Secrets Manager client.
    options: IOptions<AwsSecurityOptions>?
    Optional AWS security options.
    logger: ILogger<AwsSecretsManagerSecretStore>?
    Optional logger for diagnostics.
  • constructorAwsSecretsManagerSecretStore
    public AwsSecretsManagerSecretStore(IOptions<AwsSecurityOptions> options)

    Initializes a new instance of the `AwsSecretsManagerSecretStore` class with default null logger.

    options: IOptions<AwsSecurityOptions>
    The AWS security options.
  • constructorAwsSecretsManagerSecretStore
    public AwsSecretsManagerSecretStore(IOptions<AwsSecurityOptions> options, ILogger<AwsSecretsManagerSecretStore> logger)

    Initializes a new instance of the `AwsSecretsManagerSecretStore` class.

    options: IOptions<AwsSecurityOptions>
    The AWS security options.
    logger: ILogger<AwsSecretsManagerSecretStore>
    The logger for diagnostics and operational warnings.

    Exceptions: ArgumentNullException: `options` or `logger` is `null`; InvalidOperationException: Options lack credentials or pre-configured client

  • methodDispose
    public void Dispose()

    Releases the resources used by this instance.

  • methodGetSecretAsync
    public async ValueTask<Result<Redacted<string>>> GetSecretAsync(string secretName, CancellationToken cancellationToken = default)

    Retrieves a secret by name as a memory-safe `Redacted<T>` string container.

    secretName: string
    The unique secret key name.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the secret value.

  • methodSetSecretAsync
    public async ValueTask<Result> SetSecretAsync(string secretName, string secretValue, CancellationToken cancellationToken = default)

    Sets or updates a secret in the underlying store.

    secretName: string
    The unique secret key name.
    secretValue: string
    The secret value to persist.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating success or failure.

class

AwsSecurityOptions

Ensamblado: EricksonLopez.Security.Aws
public sealed class AwsSecurityOptions

Specifies configuration options for connecting to AWS Key Management Service (KMS) and Secrets Manager.

Miembros (6)

  • propertyCredentials
    public Amazon.Runtime.AWSCredentials? Credentials { get; set; }

    Gets or sets optional custom AWS credentials. If not specified, standard AWS credential resolution is used.

  • propertyKmsClient
    public Amazon.KeyManagementService.IAmazonKeyManagementService? KmsClient { get; set; }

    Gets or sets an explicit pre-configured `KeyManagementService.IAmazonKeyManagementService` instance. When set, this instance takes precedence over creating a new client.

  • propertyKmsKeyId
    public string? KmsKeyId { get; set; }

    Gets or sets the default AWS KMS Master Key ID or ARN.

  • propertyRegion
    public string Region { get; set; }

    Gets or sets the AWS region (e.g. "us-east-1").

  • propertySecretPrefix
    public string SecretPrefix { get; set; }

    Gets or sets an optional secret prefix for namespace isolation (e.g. "prod/").

  • propertySecretsManagerClient
    public Amazon.SecretsManager.IAmazonSecretsManager? SecretsManagerClient { get; set; }

    Gets or sets an explicit pre-configured `SecretsManager.IAmazonSecretsManager` instance. When set, this instance takes precedence over creating a new client.

EricksonLopez.Security.Azure#

3
class

AzureKeyVaultKeyStore

Ensamblado: EricksonLopez.Security.Azure
public sealed class AzureKeyVaultKeyStore : IKeyStore, IDisposable
Implementa: IDisposable, IKeyStore

Provides an `IKeyStore` adapter backed by Azure Key Vault cryptographic keys.

Notas:

Connects directly to Azure Key Vault using `SecretClient` to durably persist cryptographic keys and their associated lifecycle metadata via tags.

Miembros (8)

  • constructorAzureKeyVaultKeyStore
    public AzureKeyVaultKeyStore(IOptions<AzureKeyVaultOptions> options)

    Initializes a new instance of the `AzureKeyVaultKeyStore` class with default null logger.

    options: IOptions<AzureKeyVaultOptions>
    The Azure Key Vault configuration options.
  • constructorAzureKeyVaultKeyStore
    public AzureKeyVaultKeyStore(IOptions<AzureKeyVaultOptions> options, ILogger<AzureKeyVaultKeyStore> logger)

    Initializes a new instance of the `AzureKeyVaultKeyStore` class.

    options: IOptions<AzureKeyVaultOptions>
    The Azure Key Vault configuration options.
    logger: ILogger<AzureKeyVaultKeyStore>
    The logger for diagnostics and operational warnings.

    Exceptions: ArgumentNullException: `options` or `logger` is `null`; InvalidOperationException: Options lack VaultUri and SecretClient

  • constructorAzureKeyVaultKeyStore
    public AzureKeyVaultKeyStore(SecretClient secretClient, IOptions<AzureKeyVaultOptions>? options = null, ILogger<AzureKeyVaultKeyStore>? logger = null)

    Initializes a new instance of the `AzureKeyVaultKeyStore` class using a pre-configured `SecretClient`.

    secretClient: SecretClient
    The Azure Key Vault SecretClient.
    options: IOptions<AzureKeyVaultOptions>?
    Optional Azure Key Vault configuration options.
    logger: ILogger<AzureKeyVaultKeyStore>?
    Optional logger for diagnostics.
  • methodDispose
    public void Dispose()

    Releases the resources used by this instance.

  • methodGetKeyAsync
    public async ValueTask<Result<CryptographicKey>> GetKeyAsync(KeyIdentifier keyId, KeyVersion version, CancellationToken cancellationToken = default)

    Retrieves a cryptographic key by identifier and version.

    keyId: KeyIdentifier
    The key identifier.
    version: KeyVersion
    The key version.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the `CryptographicKey`.

  • methodListMetadataAsync
    public async ValueTask<Result<IReadOnlyList<KeyMetadata>>> ListMetadataAsync(KeyPurpose? purpose = null, CancellationToken cancellationToken = default)

    Retrieves all key metadata stored in the repository.

    purpose: KeyPurpose?
    Optional purpose filter.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a result with a list of key metadata records.

  • methodSaveKeyAsync
    public async ValueTask<Result> SaveKeyAsync(CryptographicKey key, CancellationToken cancellationToken = default)

    Persists a new cryptographic key into the key store.

    key: CryptographicKey
    The cryptographic key to save.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating success or failure.

  • methodUpdateStatusAsync
    public async ValueTask<Result> UpdateStatusAsync(KeyIdentifier keyId, KeyVersion version, KeyStatus newStatus, CancellationToken cancellationToken = default)

    Updates the lifecycle status of a specific key.

    keyId: KeyIdentifier
    The key identifier.
    version: KeyVersion
    The key version.
    newStatus: KeyStatus
    The new lifecycle status.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating the outcome.

class

AzureKeyVaultOptions

Ensamblado: EricksonLopez.Security.Azure
public sealed class AzureKeyVaultOptions

Specifies configuration options for connecting to Azure Key Vault services.

Miembros (5)

  • propertyCredential
    public global::Azure.Core.TokenCredential? Credential { get; set; }

    Gets or sets the custom Azure `Core.TokenCredential` for authenticating against Azure Key Vault.

    If not specified, `Identity.DefaultAzureCredential` is used by default when `VaultUri` is provided.

  • propertyKeyClient
    public global::Azure.Security.KeyVault.Keys.KeyClient? KeyClient { get; set; }

    Gets or sets an explicit pre-configured `Keys.KeyClient` instance. When set, this instance takes precedence over creating a new client from `VaultUri`.

  • propertySecretClient
    public global::Azure.Security.KeyVault.Secrets.SecretClient? SecretClient { get; set; }

    Gets or sets an explicit pre-configured `Secrets.SecretClient` instance. When set, this instance takes precedence over creating a new client from `VaultUri`.

  • propertySecretPrefix
    public string SecretPrefix { get; set; }

    Gets or sets an optional secret prefix for namespace isolation in Key Vault (e.g. "app-").

  • propertyVaultUri
    public Uri? VaultUri { get; set; }

    Gets or sets the Azure Key Vault Uri (e.g. "https://my-vault.vault.azure.net/").

class

AzureKeyVaultSecretStore

Ensamblado: EricksonLopez.Security.Azure
public sealed class AzureKeyVaultSecretStore : ISecretStore
Implementa: ISecretStore

Provides an `ISecretStore` adapter backed by Azure Key Vault Secrets.

Notas:

Connects directly to Azure Key Vault using `SecretClient`.

Miembros (5)

  • constructorAzureKeyVaultSecretStore
    public AzureKeyVaultSecretStore(IOptions<AzureKeyVaultOptions> options)

    Initializes a new instance of the `AzureKeyVaultSecretStore` class with default null logger.

    options: IOptions<AzureKeyVaultOptions>
    The Azure Key Vault configuration options.
  • constructorAzureKeyVaultSecretStore
    public AzureKeyVaultSecretStore(IOptions<AzureKeyVaultOptions> options, ILogger<AzureKeyVaultSecretStore> logger)

    Initializes a new instance of the `AzureKeyVaultSecretStore` class.

    options: IOptions<AzureKeyVaultOptions>
    The Azure Key Vault configuration options.
    logger: ILogger<AzureKeyVaultSecretStore>
    The logger for diagnostics and operational warnings.

    Exceptions: ArgumentNullException: `options` or `logger` is `null`; InvalidOperationException: Options lack VaultUri and SecretClient

  • constructorAzureKeyVaultSecretStore
    public AzureKeyVaultSecretStore(SecretClient secretClient, IOptions<AzureKeyVaultOptions>? options = null, ILogger<AzureKeyVaultSecretStore>? logger = null)

    Initializes a new instance of the `AzureKeyVaultSecretStore` class using a pre-configured `SecretClient`.

    secretClient: SecretClient
    The Azure Key Vault SecretClient.
    options: IOptions<AzureKeyVaultOptions>?
    Optional Azure Key Vault configuration options.
    logger: ILogger<AzureKeyVaultSecretStore>?
    Optional logger for diagnostics.
  • methodGetSecretAsync
    public async ValueTask<Result<Redacted<string>>> GetSecretAsync(string secretName, CancellationToken cancellationToken = default)

    Retrieves a secret by name as a memory-safe `Redacted<T>` string container.

    secretName: string
    The unique secret key name.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the secret value.

  • methodSetSecretAsync
    public async ValueTask<Result> SetSecretAsync(string secretName, string secretValue, CancellationToken cancellationToken = default)

    Sets or updates a secret in the underlying store.

    secretName: string
    The unique secret key name.
    secretValue: string
    The secret value to persist.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating success or failure.

EricksonLopez.Security.Cryptography#

6
class

AesGcmEncryptionEngine

Ensamblado: EricksonLopez.Security
public sealed class AesGcmEncryptionEngine : IAuthenticatedEncryptionEngine
Implementa: IAuthenticatedEncryptionEngine

Provides an implementation of `IAuthenticatedEncryptionEngine` using Advanced Encryption Standard in Galois/Counter Mode (AES-256-GCM) per NIST SP 800-38D.

Miembros (10)

  • constructorAesGcmEncryptionEngine
    public AesGcmEncryptionEngine()

    Initializes a new instance of the `AesGcmEncryptionEngine` class.

  • methodDecrypt
    public Result Decrypt(ReadOnlySpan<byte> ciphertext, ReadOnlySpan<byte> key, ReadOnlySpan<byte> nonce, ReadOnlySpan<byte> tag, ReadOnlySpan<byte> associatedData, Span<byte> plaintextDestination, out int bytesWritten)

    Decrypts and authenticates the ciphertext using the specified key, nonce, tag, and associated data into a caller-supplied destination span.

    ciphertext: ReadOnlySpan<byte>
    The encrypted payload span.
    key: ReadOnlySpan<byte>
    The cryptographic key span.
    nonce: ReadOnlySpan<byte>
    The initialization nonce span.
    tag: ReadOnlySpan<byte>
    The authentication tag span.
    associatedData: ReadOnlySpan<byte>
    The associated data span to authenticate.
    plaintextDestination: Span<byte>
    The destination buffer for decrypted bytes.
    bytesWritten: out int
    The number of decrypted bytes written to the destination.

    Retorna: A `Result` indicating success or failure (e.g. tag mismatch, tampered data).

    Security — Payload Size (GAP-01): This method does not enforce an upper bound on `ciphertext` length. When the caller allocates `plaintextDestination` based on untrusted input (e.g. network-received ciphertext), an attacker who controls the payload length can trigger large heap allocations before the authentication tag is verified, potentially causing out-of-memory conditions in constrained environments. Required mitigation: The caller MUST validate `ciphertext.Length` against an application-defined maximum before calling this method. A recommended limit is `256 * 1024 * 1024` bytes (256 MiB) for most workloads. See individual engine implementations (e.g. `AesGcmEncryptionEngine.MaxRecommendedPayloadBytes`) for suggested defaults.

  • methodEncrypt
    public Result<EncryptedData> Encrypt(ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> key, ReadOnlySpan<byte> associatedData = default)

    Encrypts the provided plaintext using authenticated encryption with the specified key, generating a fresh random nonce.

    plaintext: ReadOnlySpan<byte>
    The unencrypted data span.
    key: ReadOnlySpan<byte>
    The 256-bit cryptographic key span.
    associatedData: ReadOnlySpan<byte>
    Optional authenticated associated data.

    Retorna: A `Result<T>` containing the `EncryptedData` on success, or a failure error.

    Memory Note (AUDIT-AES-06): The returned `EncryptedData` record contains managed `byte[]` arrays for the ciphertext, authentication tag, and nonce. These arrays are heap-allocated and cannot be explicitly zeroed by the library after use \u2014 the ciphertext content will remain in memory until the next garbage collection cycle. For callers that must minimize the heap exposure window of encrypted envelope data (e.g., when building a streaming envelope protocol), prefer the span-based zero-allocation overload `Encrypt(plaintext, key, nonce, ciphertext, tag)`, which writes directly into caller-provided `Span<T>` buffers that can be zeroed or stack-allocated.

  • methodEncrypt
    public Result Encrypt(ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> key, Span<byte> nonceDestination, Span<byte> ciphertextDestination, Span<byte> tagDestination, ReadOnlySpan<byte> associatedData = default)

    Encrypts the provided plaintext into caller-provided output spans for zero heap allocations, automatically generating a fresh cryptographically secure random nonce into `nonceDestination` to guarantee nonce-misuse resistance and prevent catastrophic nonce reuse.

    plaintext: ReadOnlySpan<byte>
    The unencrypted data span.
    key: ReadOnlySpan<byte>
    The cryptographic key span.
    nonceDestination: Span<byte>
    The destination span where the freshly generated nonce is written (at least 12 bytes).
    ciphertextDestination: Span<byte>
    The destination span for encrypted bytes (must be at least plaintext.Length).
    tagDestination: Span<byte>
    The destination span for the 16-byte authentication tag.
    associatedData: ReadOnlySpan<byte>
    Optional authenticated associated data.

    Retorna: A `Result` indicating success or a cryptographic failure error.

  • propertyAlgorithm
    public AeadAlgorithm Algorithm { get; }

    Gets the AEAD algorithm implemented by this engine.

  • propertyKeySizeBytes
    public int KeySizeBytes { get; }

    Gets the required key size in bytes (e.g., 32 bytes for AES-256).

  • propertyNonceSizeBytes
    public int NonceSizeBytes { get; }

    Gets the required nonce size in bytes (e.g., 12 bytes).

  • propertyTagSizeBytes
    public int TagSizeBytes { get; }

    Gets the required authentication tag size in bytes (e.g., 16 bytes).

  • fieldMaxRecommendedPayloadBytes
    public const int MaxRecommendedPayloadBytes

    Gets the maximum allowed payload size in bytes (256 MiB) enforced by the engine on Encrypt and Decrypt operations to prevent asymmetric memory exhaustion DoS attacks (GAP-01 / REM-001).

  • fieldShared
    public static readonly AesGcmEncryptionEngine Shared

    Gets the shared singleton instance of `AesGcmEncryptionEngine`.

class

BinarySecurityEnvelopeSerializer

Ensamblado: EricksonLopez.Security
public sealed class BinarySecurityEnvelopeSerializer : ISecurityEnvelopeSerializer
Implementa: ISecurityEnvelopeSerializer

Provides a binary serializer and parser for `SecurityEnvelope` that enforces strict byte-level validation, version matching, and buffer boundaries.

Miembros (6)

  • constructorBinarySecurityEnvelopeSerializer
    public BinarySecurityEnvelopeSerializer()

    Initializes a new instance of the `BinarySecurityEnvelopeSerializer` class.

  • methodDeserialize
    public Result<SecurityEnvelope> Deserialize(ReadOnlySpan<byte> payload)

    Deserializes a binary payload into a validated `SecurityEnvelope`.

    payload: ReadOnlySpan<byte>
    The binary serialized payload span.

    Retorna: A `Result<T>` containing the reconstructed `SecurityEnvelope` or an error.

  • methodSerialize
    public byte[] Serialize(SecurityEnvelope envelope)

    Serializes a `SecurityEnvelope` into a newly allocated binary byte array.

    envelope: SecurityEnvelope
    The envelope to serialize.

    Retorna: A byte array containing the serialized envelope.

  • methodTrySerialize
    public bool TrySerialize(SecurityEnvelope envelope, Span<byte> destination, out int bytesWritten)

    Serializes a `SecurityEnvelope` into a caller-supplied destination span for zero allocations.

    envelope: SecurityEnvelope
    The envelope to serialize.
    destination: Span<byte>
    The destination byte span.
    bytesWritten: out int
    The total number of bytes written to the destination.

    Retorna: `true` if the destination buffer was large enough; otherwise, `false`.

  • fieldMaxCiphertextPayloadBytes
    public const int MaxCiphertextPayloadBytes

    Defines the maximum permitted ciphertext payload size in bytes (64 MB) to prevent memory exhaustion DoS attacks.

  • fieldShared
    public static readonly BinarySecurityEnvelopeSerializer Shared

    Gets the shared singleton instance of `BinarySecurityEnvelopeSerializer`.

class

BoundedPasswordHasher

Ensamblado: EricksonLopez.Security.Cryptography
public sealed class BoundedPasswordHasher : IAsyncPasswordHasher, IDisposable
Implementa: IAsyncPasswordHasher, IDisposable

Decorates an `IPasswordHasher` (such as 64 MiB Argon2id) with a process-wide `SemaphoreSlim` concurrency gate to prevent container OOM kills and thread-pool starvation under credential-stuffing bursts.

Miembros (11)

  • constructorBoundedPasswordHasher
    public BoundedPasswordHasher(IPasswordHasher inner, BoundedPasswordHasherOptions? options = null)

    Initializes a new instance of the `BoundedPasswordHasher` class.

    inner: IPasswordHasher
    The inner KDF password hasher.
    options: BoundedPasswordHasherOptions?
    Optional concurrency options.

    Exceptions: ArgumentNullException: `inner` is `null`.; ArgumentOutOfRangeException: `BoundedPasswordHasherOptions.MaxConcurrency` or `BoundedPasswordHasherOptions.AcquireTimeout` is non-positive.

  • methodDispose
    public void Dispose()

    Inherits documentation from base type or interface.

  • methodHashPassword
    public string HashPassword(ReadOnlySpan<char> password)

    Inherits documentation from base type or interface.

    password: ReadOnlySpan<char>
  • methodHashPassword
    public string HashPassword(string password)

    Computes a salted password hash synchronously using the bounded concurrency gate.

    password: string
    The plaintext password string.

    Retorna: The encoded password hash.

  • methodHashPasswordAsync
    public async ValueTask<string> HashPasswordAsync(string password, CancellationToken ct = default)

    Asynchronously computes a cryptographically salted password hash while respecting bounded concurrency gates.

    password: string
    The plaintext password to hash.
    ct: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A value task containing the encoded password hash string.

  • methodNeedsRehash
    public bool NeedsRehash(string hashedPassword)

    Inherits documentation from base type or interface.

    hashedPassword: string
  • methodVerifyPassword
    public PasswordVerificationResult VerifyPassword(ReadOnlySpan<char> password, string hashedPassword)

    Inherits documentation from base type or interface.

    password: ReadOnlySpan<char>
    hashedPassword: string
  • methodVerifyPassword
    public PasswordVerificationResult VerifyPassword(string password, string hashedPassword)

    Verifies a plaintext password synchronously using the bounded concurrency gate.

    password: string
    The candidate plaintext password.
    hashedPassword: string
    The stored password hash.

    Retorna: The `PasswordVerificationResult`.

  • methodVerifyPasswordAsync
    public async ValueTask<PasswordVerificationResult> VerifyPasswordAsync(string password, string hashedPassword, CancellationToken ct = default)

    Asynchronously verifies a plaintext password against a stored password hash while respecting bounded concurrency gates.

    password: string
    The candidate plaintext password.
    hashedPassword: string
    The stored password hash string.
    ct: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A value task containing the `PasswordVerificationResult`.

  • propertyAlgorithm
    public PasswordHashAlgorithm Algorithm { get; }

    Inherits documentation from base type or interface.

  • propertyAvailableSlots
    public int AvailableSlots { get; }

    Gets the current number of available KDF execution slots.

class

BoundedPasswordHasherOptions

Ensamblado: EricksonLopez.Security.Cryptography
public sealed class BoundedPasswordHasherOptions

Configures the concurrency semaphore ceiling and wait timeout for `BoundedPasswordHasher`.

Miembros (2)

  • propertyAcquireTimeout
    public TimeSpan AcquireTimeout { get; set; }

    Gets or sets the maximum duration a caller waits to acquire a KDF concurrency slot before failing closed. Defaults to 15 seconds.

  • propertyMaxConcurrency
    public int MaxConcurrency { get; set; }

    Gets or sets the maximum number of simultaneous password hashing/verification evaluations allowed per process. Defaults to `Math.Clamp(Environment.ProcessorCount * 2, 2, 16)`.

class

ChaCha20Poly1305EncryptionEngine

Ensamblado: EricksonLopez.Security
public sealed class ChaCha20Poly1305EncryptionEngine : IAuthenticatedEncryptionEngine
Implementa: IAuthenticatedEncryptionEngine

Provides an authenticated encryption engine implementing ChaCha20-Poly1305 (`AeadAlgorithm.ChaCha20Poly1305`). Utilizes a 256-bit key, 96-bit nonce, and 128-bit authentication tag.

Miembros (10)

  • methodDecrypt
    public Result Decrypt(ReadOnlySpan<byte> ciphertext, ReadOnlySpan<byte> key, ReadOnlySpan<byte> nonce, ReadOnlySpan<byte> tag, ReadOnlySpan<byte> associatedData, Span<byte> plaintextDestination, out int bytesWritten)

    Decrypts and authenticates the ciphertext using the specified key, nonce, tag, and associated data into a caller-supplied destination span.

    ciphertext: ReadOnlySpan<byte>
    The encrypted payload span.
    key: ReadOnlySpan<byte>
    The cryptographic key span.
    nonce: ReadOnlySpan<byte>
    The initialization nonce span.
    tag: ReadOnlySpan<byte>
    The authentication tag span.
    associatedData: ReadOnlySpan<byte>
    The associated data span to authenticate.
    plaintextDestination: Span<byte>
    The destination buffer for decrypted bytes.
    bytesWritten: out int
    The number of decrypted bytes written to the destination.

    Retorna: A `Result` indicating success or failure (e.g. tag mismatch, tampered data).

    Security — Payload Size (GAP-01): This method does not enforce an upper bound on `ciphertext` length. When the caller allocates `plaintextDestination` based on untrusted input (e.g. network-received ciphertext), an attacker who controls the payload length can trigger large heap allocations before the authentication tag is verified, potentially causing out-of-memory conditions in constrained environments. Required mitigation: The caller MUST validate `ciphertext.Length` against an application-defined maximum before calling this method. A recommended limit is `256 * 1024 * 1024` bytes (256 MiB) for most workloads. See individual engine implementations (e.g. `AesGcmEncryptionEngine.MaxRecommendedPayloadBytes`) for suggested defaults.

  • methodEncrypt
    public Result<EncryptedData> Encrypt(ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> key, ReadOnlySpan<byte> associatedData = default)

    Encrypts the provided plaintext using authenticated encryption with the specified key, generating a fresh random nonce.

    plaintext: ReadOnlySpan<byte>
    The unencrypted data span.
    key: ReadOnlySpan<byte>
    The 256-bit cryptographic key span.
    associatedData: ReadOnlySpan<byte>
    Optional authenticated associated data.

    Retorna: A `Result<T>` containing the `EncryptedData` on success, or a failure error.

  • methodEncrypt
    public Result Encrypt(ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> key, Span<byte> nonceDestination, Span<byte> ciphertextDestination, Span<byte> tagDestination, ReadOnlySpan<byte> associatedData = default)

    Encrypts the provided plaintext into caller-provided output spans for zero heap allocations, automatically generating a fresh cryptographically secure random nonce into `nonceDestination` to guarantee nonce-misuse resistance and prevent catastrophic nonce reuse.

    plaintext: ReadOnlySpan<byte>
    The unencrypted data span.
    key: ReadOnlySpan<byte>
    The cryptographic key span.
    nonceDestination: Span<byte>
    The destination span where the freshly generated nonce is written (at least 12 bytes).
    ciphertextDestination: Span<byte>
    The destination span for encrypted bytes (must be at least plaintext.Length).
    tagDestination: Span<byte>
    The destination span for the 16-byte authentication tag.
    associatedData: ReadOnlySpan<byte>
    Optional authenticated associated data.

    Retorna: A `Result` indicating success or a cryptographic failure error.

  • propertyAlgorithm
    public AeadAlgorithm Algorithm { get; }

    Gets the AEAD algorithm implemented by this engine.

  • propertyIsSupported
    public static bool IsSupported { get; }

    Gets a value indicating whether ChaCha20-Poly1305 is supported on the current platform.

  • propertyKeySizeBytes
    public int KeySizeBytes { get; }

    Gets the required key size in bytes (e.g., 32 bytes for AES-256).

  • propertyNonceSizeBytes
    public int NonceSizeBytes { get; }

    Gets the required nonce size in bytes (e.g., 12 bytes).

  • propertyTagSizeBytes
    public int TagSizeBytes { get; }

    Gets the required authentication tag size in bytes (e.g., 16 bytes).

  • fieldMaxRecommendedPayloadBytes
    public const int MaxRecommendedPayloadBytes

    Gets the maximum allowed payload size in bytes (256 MiB) enforced by the engine on Encrypt and Decrypt operations to prevent asymmetric memory exhaustion DoS attacks (GAP-01 / REM-001).

  • fieldShared
    public static readonly ChaCha20Poly1305EncryptionEngine Shared

    Gets the shared singleton instance of `ChaCha20Poly1305EncryptionEngine`.

class

HkdfAesGcmEncryptionEngine

Ensamblado: EricksonLopez.Security
public sealed class HkdfAesGcmEncryptionEngine : IAuthenticatedEncryptionEngine
Implementa: IAuthenticatedEncryptionEngine

Provides HKDF-enhanced AES-256-GCM authenticated encryption that derives a unique ephemeral 256-bit key for every encryption operation via HKDF-SHA512, ensuring forward-secrecy-like key isolation and replay resistance through per-operation key derivation.

Miembros (22)

  • constructorHkdfAesGcmEncryptionEngine
    public HkdfAesGcmEncryptionEngine(bool requireAssociatedData = false)

    Initializes a new instance of the `HkdfAesGcmEncryptionEngine` class.

    requireAssociatedData: bool
    When `true`, empty associated data is rejected fail-closed with `Security.AssociatedDataMismatch`.
  • methodDecrypt
    public Result Decrypt(ReadOnlySpan<byte> ciphertext, ReadOnlySpan<byte> key, ReadOnlySpan<byte> nonce, ReadOnlySpan<byte> tag, ReadOnlySpan<byte> associatedData, Span<byte> plaintextDestination, out int bytesWritten)

    Decrypts and authenticates the ciphertext using the specified key, nonce, tag, and associated data into a caller-supplied destination span.

    ciphertext: ReadOnlySpan<byte>
    The encrypted payload span.
    key: ReadOnlySpan<byte>
    The cryptographic key span.
    nonce: ReadOnlySpan<byte>
    The initialization nonce span.
    tag: ReadOnlySpan<byte>
    The authentication tag span.
    associatedData: ReadOnlySpan<byte>
    The associated data span to authenticate.
    plaintextDestination: Span<byte>
    The destination buffer for decrypted bytes.
    bytesWritten: out int
    The number of decrypted bytes written to the destination.

    Retorna: A `Result` indicating success or failure (e.g. tag mismatch, tampered data).

    Security — Payload Size (GAP-01): This method does not enforce an upper bound on `ciphertext` length. When the caller allocates `plaintextDestination` based on untrusted input (e.g. network-received ciphertext), an attacker who controls the payload length can trigger large heap allocations before the authentication tag is verified, potentially causing out-of-memory conditions in constrained environments. Required mitigation: The caller MUST validate `ciphertext.Length` against an application-defined maximum before calling this method. A recommended limit is `256 * 1024 * 1024` bytes (256 MiB) for most workloads. See individual engine implementations (e.g. `AesGcmEncryptionEngine.MaxRecommendedPayloadBytes`) for suggested defaults.

  • methodDecryptStringWithAssociatedData
    public Result<string> DecryptStringWithAssociatedData(string ciphertextBase64, ReadOnlySpan<byte> key, ReadOnlySpan<byte> associatedData)

    Decrypts and authenticates a Base64-encoded packed AEAD envelope back into a UTF-8 string using mandatory non-empty `associatedData`.

    ciphertextBase64: string
    The Base64-encoded packed AEAD envelope.
    key: ReadOnlySpan<byte>
    The 32-byte root encryption key.
    associatedData: ReadOnlySpan<byte>
    Mandatory non-empty associated data bytes.

    Retorna: A `Result<T>` containing the decrypted UTF-8 string on success, or a typed security error.

  • methodDecryptStringWithAssociatedData
    public Result<string> DecryptStringWithAssociatedData(string ciphertextBase64, ReadOnlySpan<byte> key, string? associatedDataContext)

    Decrypts and authenticates a Base64-encoded packed AEAD envelope back into a UTF-8 string using mandatory non-empty `associatedDataContext`.

    ciphertextBase64: string
    The Base64-encoded packed AEAD envelope.
    key: ReadOnlySpan<byte>
    The 32-byte root encryption key.
    associatedDataContext: string?
    Mandatory non-empty UTF-8 context string bound as AAD.

    Retorna: A `Result<T>` containing the decrypted UTF-8 string on success, or a typed security error.

  • methodDecryptWithAssociatedData
    public Result<byte[]> DecryptWithAssociatedData(ReadOnlySpan<byte> packedPayload, ReadOnlySpan<byte> key, ReadOnlySpan<byte> associatedData)

    Decrypts and authenticates a packed envelope `[Nonce(12B) | Tag(16B) | Ciphertext(NB)]` bound to mandatory non-empty `associatedData`.

    packedPayload: ReadOnlySpan<byte>
    The packed AEAD envelope bytes.
    key: ReadOnlySpan<byte>
    The 32-byte root encryption key.
    associatedData: ReadOnlySpan<byte>
    Mandatory non-empty associated data bytes.

    Retorna: A `Result<T>` containing the decrypted plaintext bytes on success, or a typed security error.

  • methodDecryptWithAssociatedData
    public Result<byte[]> DecryptWithAssociatedData(ReadOnlySpan<byte> packedPayload, ReadOnlySpan<byte> key, string? associatedDataContext)

    Decrypts and authenticates a packed envelope `[Nonce(12B) | Tag(16B) | Ciphertext(NB)]` bound to mandatory non-empty `associatedDataContext`.

    packedPayload: ReadOnlySpan<byte>
    The packed AEAD envelope bytes.
    key: ReadOnlySpan<byte>
    The 32-byte root encryption key.
    associatedDataContext: string?
    Mandatory non-empty UTF-8 context string bound as AAD.

    Retorna: A `Result<T>` containing the decrypted plaintext bytes on success, or a typed security error.

  • methodEncrypt
    public Result<EncryptedData> Encrypt(ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> key, ReadOnlySpan<byte> associatedData = default)

    Encrypts the provided plaintext using authenticated encryption with the specified key, generating a fresh random nonce.

    plaintext: ReadOnlySpan<byte>
    The unencrypted data span.
    key: ReadOnlySpan<byte>
    The 256-bit cryptographic key span.
    associatedData: ReadOnlySpan<byte>
    Optional authenticated associated data.

    Retorna: A `Result<T>` containing the `EncryptedData` on success, or a failure error.

  • methodEncrypt
    public Result Encrypt(ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> key, Span<byte> nonceDestination, Span<byte> ciphertextDestination, Span<byte> tagDestination, ReadOnlySpan<byte> associatedData = default)

    Encrypts the provided plaintext into caller-provided output spans for zero heap allocations, automatically generating a fresh cryptographically secure random nonce into `nonceDestination` to guarantee nonce-misuse resistance and prevent catastrophic nonce reuse.

    plaintext: ReadOnlySpan<byte>
    The unencrypted data span.
    key: ReadOnlySpan<byte>
    The cryptographic key span.
    nonceDestination: Span<byte>
    The destination span where the freshly generated nonce is written (at least 12 bytes).
    ciphertextDestination: Span<byte>
    The destination span for encrypted bytes (must be at least plaintext.Length).
    tagDestination: Span<byte>
    The destination span for the 16-byte authentication tag.
    associatedData: ReadOnlySpan<byte>
    Optional authenticated associated data.

    Retorna: A `Result` indicating success or a cryptographic failure error.

  • methodEncryptStringWithAssociatedData
    public Result<string> EncryptStringWithAssociatedData(string plaintext, ReadOnlySpan<byte> key, ReadOnlySpan<byte> associatedData)

    Encrypts a non-empty UTF-8 string into a Base64-encoded packed AEAD envelope bound to mandatory non-empty `associatedData`.

    plaintext: string
    The non-empty UTF-8 string to encrypt.
    key: ReadOnlySpan<byte>
    The 32-byte root encryption key.
    associatedData: ReadOnlySpan<byte>
    Mandatory non-empty associated data bytes.

    Retorna: A `Result<T>` containing the Base64 ciphertext string on success, or a typed security error.

  • methodEncryptStringWithAssociatedData
    public Result<string> EncryptStringWithAssociatedData(string plaintext, ReadOnlySpan<byte> key, string? associatedDataContext)

    Encrypts a non-empty UTF-8 string into a Base64-encoded packed AEAD envelope bound to mandatory non-empty `associatedDataContext`.

    plaintext: string
    The non-empty UTF-8 string to encrypt.
    key: ReadOnlySpan<byte>
    The 32-byte root encryption key.
    associatedDataContext: string?
    Mandatory non-empty UTF-8 context string bound as AAD.

    Retorna: A `Result<T>` containing the Base64 ciphertext string on success, or a typed security error.

  • methodEncryptWithAssociatedData
    public Result<byte[]> EncryptWithAssociatedData(ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> key, ReadOnlySpan<byte> associatedData)

    Encrypts `plaintext` into a packed envelope `[Nonce(12B) | Tag(16B) | Ciphertext(NB)]` bound to mandatory non-empty `associatedData`.

    plaintext: ReadOnlySpan<byte>
    The plaintext bytes to encrypt.
    key: ReadOnlySpan<byte>
    The 32-byte root encryption key.
    associatedData: ReadOnlySpan<byte>
    Mandatory non-empty associated data bytes.

    Retorna: A `Result<T>` containing the packed AEAD envelope bytes on success, or a typed security error.

  • methodEncryptWithAssociatedData
    public Result<byte[]> EncryptWithAssociatedData(ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> key, string? associatedDataContext)

    Encrypts `plaintext` into a packed envelope `[Nonce(12B) | Tag(16B) | Ciphertext(NB)]` bound to mandatory non-empty `associatedDataContext`.

    plaintext: ReadOnlySpan<byte>
    The plaintext bytes to encrypt.
    key: ReadOnlySpan<byte>
    The 32-byte root encryption key.
    associatedDataContext: string?
    Mandatory non-empty UTF-8 context string bound as AAD.

    Retorna: A `Result<T>` containing the packed AEAD envelope bytes on success, or a typed security error.

  • propertyAlgorithm
    public AeadAlgorithm Algorithm { get; }

    Gets the AEAD algorithm implemented by this engine.

  • propertyIsQuantumResistant
    public static bool IsQuantumResistant { get; }

    Gets a value indicating whether this engine provides true quantum resistance.

  • propertyKeySizeBytes
    public int KeySizeBytes { get; }

    Gets the required key size in bytes (e.g., 32 bytes for AES-256).

  • propertyNonceSizeBytes
    public int NonceSizeBytes { get; }

    Gets the required nonce size in bytes (e.g., 12 bytes).

  • propertyRequireAssociatedData
    public bool RequireAssociatedData { get; }

    Gets a value indicating whether non-empty associated data (AAD) is mandatory on all encrypt and decrypt operations.

  • propertySubstrateDescription
    public static string SubstrateDescription { get; }

    Gets the cryptographic substrate name backing this engine.

  • propertyTagSizeBytes
    public int TagSizeBytes { get; }

    Gets the required authentication tag size in bytes (e.g., 16 bytes).

  • fieldMaxRecommendedPayloadBytes
    public const int MaxRecommendedPayloadBytes

    Gets the maximum allowed payload size in bytes (256 MiB) enforced by the engine on Encrypt and Decrypt operations to prevent asymmetric memory exhaustion DoS attacks (GAP-01 / REM-001).

  • fieldShared
    public static readonly HkdfAesGcmEncryptionEngine Shared

    Gets the shared singleton instance of `HkdfAesGcmEncryptionEngine` with optional AAD.

  • fieldStrictAad
    public static readonly HkdfAesGcmEncryptionEngine StrictAad

    Gets the strict shared singleton instance of `HkdfAesGcmEncryptionEngine` that enforces non-empty AAD on every call.

EricksonLopez.Security.Cryptography.Encryption#

2
class

AesGcmAuthenticatedEncryptionEngine

Ensamblado: EricksonLopez.Security.Cryptography
public sealed class AesGcmAuthenticatedEncryptionEngine(ICryptographicRandomNumberGenerator random) : IAuthenticatedEncryptionEngine
Implementa: IAuthenticatedEncryptionEngine

Provides high-performance, low-allocation AES-GCM (256-bit) authenticated encryption.

Miembros (18)

  • constructorAesGcmAuthenticatedEncryptionEngine
    public AesGcmAuthenticatedEncryptionEngine()

    Initializes a new instance of the `AesGcmAuthenticatedEncryptionEngine` class backed by the default OS CSPRNG.

  • constructorAesGcmAuthenticatedEncryptionEngine
    public AesGcmAuthenticatedEncryptionEngine(ICryptographicRandomNumberGenerator random)

    Initializes a new instance of AesGcmAuthenticatedEncryptionEngine.

    random: ICryptographicRandomNumberGenerator
    The cryptographic random number generator that generates nonces.
  • methodDecrypt
    public Result Decrypt(ReadOnlySpan<byte> ciphertext, ReadOnlySpan<byte> key, ReadOnlySpan<byte> nonce, ReadOnlySpan<byte> tag, ReadOnlySpan<byte> associatedData, Span<byte> plaintextDestination, out int bytesWritten)

    Decrypts and authenticates the ciphertext using the specified key, nonce, tag, and associated data into a caller-supplied destination span.

    ciphertext: ReadOnlySpan<byte>
    The encrypted payload span.
    key: ReadOnlySpan<byte>
    The cryptographic key span.
    nonce: ReadOnlySpan<byte>
    The initialization nonce span.
    tag: ReadOnlySpan<byte>
    The authentication tag span.
    associatedData: ReadOnlySpan<byte>
    The associated data span to authenticate.
    plaintextDestination: Span<byte>
    The destination buffer for decrypted bytes.
    bytesWritten: out int
    The number of decrypted bytes written to the destination.

    Retorna: A `Result` indicating success or failure (e.g. tag mismatch, tampered data).

    Security — Payload Size (GAP-01): This method does not enforce an upper bound on `ciphertext` length. When the caller allocates `plaintextDestination` based on untrusted input (e.g. network-received ciphertext), an attacker who controls the payload length can trigger large heap allocations before the authentication tag is verified, potentially causing out-of-memory conditions in constrained environments. Required mitigation: The caller MUST validate `ciphertext.Length` against an application-defined maximum before calling this method. A recommended limit is `256 * 1024 * 1024` bytes (256 MiB) for most workloads. See individual engine implementations (e.g. `AesGcmEncryptionEngine.MaxRecommendedPayloadBytes`) for suggested defaults.

  • methodDecryptDecimal
    public Result<decimal> DecryptDecimal(EncryptedData encryptedData, ReadOnlySpan<byte> key, ReadOnlySpan<byte> associatedData = default)

    Decrypts and authenticates an `EncryptedData` payload back into a `decimal` value.

    encryptedData: EncryptedData
    The encrypted payload containing ciphertext, tag, and nonce.
    key: ReadOnlySpan<byte>
    The 32-byte (256-bit) encryption key.
    associatedData: ReadOnlySpan<byte>
    Optional authenticated associated data.

    Retorna: A `Result<Decimal>` containing the decrypted decimal value or an error.

  • methodDecryptFromPackedBase64
    public string DecryptFromPackedBase64(string? ciphertextBase64, ReadOnlySpan<byte> key)

    Decrypts a packed Base64 envelope `[Nonce(12B) | Tag(16B) | Ciphertext(NB)]` back into a UTF-8 string.

    ciphertextBase64: string?
    The Base64-encoded envelope.
    key: ReadOnlySpan<byte>
    The 32-byte (256-bit) encryption key.

    Retorna: The decrypted plaintext string, or `string.Empty` when `ciphertextBase64` is empty.

    Exceptions: CryptographicException: The payload is truncated, tampered with, or key is invalid

  • methodDecryptFromPackedBase64
    public Result<string> DecryptFromPackedBase64(string ciphertextBase64, ReadOnlySpan<byte> key, ReadOnlySpan<byte> associatedData)

    Decrypts and authenticates a packed Base64 envelope `[Nonce(12B) | Tag(16B) | Ciphertext(NB)]` back into a UTF-8 string bound to mandatory non-empty `associatedData`.

    ciphertextBase64: string
    The Base64-encoded envelope.
    key: ReadOnlySpan<byte>
    The 32-byte (256-bit) encryption key.
    associatedData: ReadOnlySpan<byte>
    Mandatory non-empty associated data bytes.

    Retorna: A `Result<T>` containing the decrypted UTF-8 string on success, or a typed security error.

  • methodDecryptFromPackedBase64
    public Result<string> DecryptFromPackedBase64(string ciphertextBase64, ReadOnlySpan<byte> key, string? associatedDataContext)

    Decrypts and authenticates a packed Base64 envelope `[Nonce(12B) | Tag(16B) | Ciphertext(NB)]` back into a UTF-8 string bound to mandatory non-empty `associatedDataContext`.

    ciphertextBase64: string
    The Base64-encoded envelope.
    key: ReadOnlySpan<byte>
    The 32-byte (256-bit) encryption key.
    associatedDataContext: string?
    Mandatory non-empty UTF-8 context string bound as AAD.

    Retorna: A `Result<T>` containing the decrypted UTF-8 string on success, or a typed security error.

  • methodEncrypt
    public Result<EncryptedData> Encrypt(ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> key, ReadOnlySpan<byte> associatedData = default)

    Encrypts the provided plaintext using authenticated encryption with the specified key, generating a fresh random nonce.

    plaintext: ReadOnlySpan<byte>
    The unencrypted data span.
    key: ReadOnlySpan<byte>
    The 256-bit cryptographic key span.
    associatedData: ReadOnlySpan<byte>
    Optional authenticated associated data.

    Retorna: A `Result<T>` containing the `EncryptedData` on success, or a failure error.

  • methodEncrypt
    public Result Encrypt(ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> key, Span<byte> nonceDestination, Span<byte> ciphertextDestination, Span<byte> tagDestination, ReadOnlySpan<byte> associatedData = default)

    Encrypts the provided plaintext into caller-provided output spans for zero heap allocations, automatically generating a fresh cryptographically secure random nonce into `nonceDestination` to guarantee nonce-misuse resistance and prevent catastrophic nonce reuse.

    plaintext: ReadOnlySpan<byte>
    The unencrypted data span.
    key: ReadOnlySpan<byte>
    The cryptographic key span.
    nonceDestination: Span<byte>
    The destination span where the freshly generated nonce is written (at least 12 bytes).
    ciphertextDestination: Span<byte>
    The destination span for encrypted bytes (must be at least plaintext.Length).
    tagDestination: Span<byte>
    The destination span for the 16-byte authentication tag.
    associatedData: ReadOnlySpan<byte>
    Optional authenticated associated data.

    Retorna: A `Result` indicating success or a cryptographic failure error.

  • methodEncryptDecimal
    public Result<EncryptedData> EncryptDecimal(decimal value, ReadOnlySpan<byte> key, ReadOnlySpan<byte> associatedData = default)

    Encrypts a `decimal` value using invariant string formatting and AES-256-GCM.

    value: decimal
    The decimal value to encrypt.
    key: ReadOnlySpan<byte>
    The 32-byte (256-bit) encryption key.
    associatedData: ReadOnlySpan<byte>
    Optional authenticated associated data.

    Retorna: A `Result<EncryptedData>` containing the encrypted decimal payload.

  • methodEncryptToPackedBase64
    public string EncryptToPackedBase64(string? plaintext, ReadOnlySpan<byte> key)

    Encrypts a UTF-8 plaintext string into a packed Base64 envelope `[Nonce(12B) | Tag(16B) | Ciphertext(NB)]`.

    plaintext: string?
    The plaintext string to encrypt.
    key: ReadOnlySpan<byte>
    The 32-byte (256-bit) encryption key.

    Retorna: The Base64-encoded envelope, or `string.Empty` when `plaintext` is empty.

    Exceptions: CryptographicException: The encryption operation failed or the key length is invalid

  • methodEncryptToPackedBase64
    public Result<string> EncryptToPackedBase64(string plaintext, ReadOnlySpan<byte> key, ReadOnlySpan<byte> associatedData)

    Encrypts a non-empty UTF-8 plaintext string into a packed Base64 envelope `[Nonce(12B) | Tag(16B) | Ciphertext(NB)]` bound to mandatory non-empty `associatedData`.

    plaintext: string
    The non-empty plaintext string to encrypt.
    key: ReadOnlySpan<byte>
    The 32-byte (256-bit) encryption key.
    associatedData: ReadOnlySpan<byte>
    Mandatory non-empty associated data bytes.

    Retorna: A `Result<T>` containing the Base64-encoded envelope on success, or a typed security error.

  • methodEncryptToPackedBase64
    public Result<string> EncryptToPackedBase64(string plaintext, ReadOnlySpan<byte> key, string? associatedDataContext)

    Encrypts a non-empty UTF-8 plaintext string into a packed Base64 envelope `[Nonce(12B) | Tag(16B) | Ciphertext(NB)]` bound to mandatory non-empty `associatedDataContext`.

    plaintext: string
    The non-empty plaintext string to encrypt.
    key: ReadOnlySpan<byte>
    The 32-byte (256-bit) encryption key.
    associatedDataContext: string?
    Mandatory non-empty UTF-8 context string bound as AAD.

    Retorna: A `Result<T>` containing the Base64-encoded envelope on success, or a typed security error.

  • propertyAlgorithm
    public AeadAlgorithm Algorithm { get; }

    Gets the AEAD algorithm implemented by this engine (`AeadAlgorithm.Aes256Gcm`).

  • propertyKeySizeBytes
    public int KeySizeBytes { get; }

    Gets the required key size in bytes (32 bytes / 256 bits).

  • propertyNonceSizeBytes
    public int NonceSizeBytes { get; }

    Gets the required nonce (initialization vector) size in bytes (12 bytes / 96 bits).

  • propertyTagSizeBytes
    public int TagSizeBytes { get; }

    Gets the authentication tag size in bytes (16 bytes / 128 bits).

  • fieldShared
    public static readonly AesGcmAuthenticatedEncryptionEngine Shared

    Gets the default thread-safe shared singleton instance backed by OS CSPRNG randomness.

class

HmacBlindIndexService

Ensamblado: EricksonLopez.Security.Cryptography
public sealed class HmacBlindIndexService : IBlindIndexService
Implementa: IBlindIndexService

Provides HKDF-SHA256 + HMAC-SHA256 deterministic blind indexing for encrypted PII lookup columns.

Miembros (4)

  • constructorHmacBlindIndexService
    public HmacBlindIndexService(byte[] masterKey, string hkdfInfo = DefaultHkdfInfo)

    Initializes a new instance of the `HmacBlindIndexService` class by deriving a 256-bit subkey from the provided 256-bit master key via HKDF-SHA256.

    masterKey: byte[]
    The 32-byte (256-bit) master key.
    hkdfInfo: string
    The HKDF info domain-separation label.

    Exceptions: ArgumentNullException: `masterKey` or `hkdfInfo` is `null`; ArgumentException: `masterKey` is not 32 bytes long

  • methodComputeBlindIndex
    public string ComputeBlindIndex(string? normalizedPlaintext)

    Computes an uppercase hexadecimal HMAC-SHA256 blind index for the normalized plaintext. Returns `string.Empty` when the input is `null` or whitespace.

    normalizedPlaintext: string?
    The plaintext value to normalize and hash.

    Retorna: A 64-character uppercase hexadecimal HMAC-SHA256 digest, or `string.Empty`.

  • methodComputeExactBlindIndex
    public string ComputeExactBlindIndex(string? normalizedValue)

    Computes a deterministic 64-character lowercase hexadecimal HKDF+HMAC-SHA256 blind index over the exact trimmed UTF-8 string without stripping punctuation or altering case beyond optional caller normalization (ideal for normalized email addresses).

    normalizedValue: string?
    The caller-normalized value (for example, `email.Trim().ToLowerInvariant()`).

    Retorna: A 64-character lowercase hexadecimal HMAC-SHA256 digest, or `string.Empty` when null or whitespace.

  • fieldDefaultHkdfInfo
    public const string DefaultHkdfInfo

    Default HKDF context info string for deriving the blind index subkey.

EricksonLopez.Security.Cryptography.Passwords#

2
class

Argon2idPasswordHasher

Ensamblado: EricksonLopez.Security.Cryptography
public sealed class Argon2idPasswordHasher : IPasswordHasher, IDisposable
Implementa: IDisposable, IPasswordHasher

Provides canonical Argon2id password hashing per RFC 9106 with SemaphoreSlim admission throttling, configurable memory ceilings, and exception-free Unicode normalization.

Miembros (15)

  • constructorArgon2idPasswordHasher
    public Argon2idPasswordHasher(int memorySizeKb = 65536, int iterations = 3, int parallelism = 4, int saltSizeBytes = 16, int maxAllowedMemoryCost = DefaultMaxAllowedMemoryCost, int maxConcurrency = 0, IConstantTimeComparer? comparer = null, ICryptographicRandomNumberGenerator? random = null)

    Initializes a new instance of the `Argon2idPasswordHasher` class with the specified cost parameters.

    memorySizeKb: int
    The memory cost in kibibytes (KiB). Must be between 1024 and 65536.
    iterations: int
    The time cost in iterations. Must be between 1 and 10.
    parallelism: int
    The degree of parallelism. Must be between 1 and 16.
    saltSizeBytes: int
    The size of the random salt in bytes. Must be between 8 and 64.
    maxAllowedMemoryCost: int
    The maximum memory cost accepted during verification.
    maxConcurrency: int
    The maximum concurrent Argon2id executions allowed (0 for shared pool).
    comparer: IConstantTimeComparer?
    Optional constant-time comparer.
    random: ICryptographicRandomNumberGenerator?
    Optional cryptographic random number generator.

    Exceptions: ArgumentOutOfRangeException: Any parameter is outside its permitted range

  • methodDispose
    public void Dispose()

    Disposes the underlying throttle resources if owned.

  • methodHashPassword
    public string HashPassword(ReadOnlySpan<char> password)

    Computes a cryptographically salted and parameterized password hash for the specified password.

    password: ReadOnlySpan<char>
    The plaintext password character span. Must not exceed 256 characters.

    Retorna: A standardized, self-describing password hash string.

    Exceptions: ArgumentOutOfRangeException: `password` length exceeds 256 characters

  • methodNeedsRehash
    public bool NeedsRehash(string hashedPassword)

    Determines whether the given stored password hash requires rehashing due to parameter updates or algorithm evolution.

    hashedPassword: string
    The stored hash string to evaluate

    Retorna: `true` if the hash should be regenerated with current parameters; otherwise, `false`.

  • methodVerifyPassword
    public PasswordVerificationResult VerifyPassword(ReadOnlySpan<char> password, string hashedPassword)

    Verifies a plaintext password against a stored hashed password using constant-time evaluation.

    password: ReadOnlySpan<char>
    The candidate password character span to verify
    hashedPassword: string
    The stored hashed password string to evaluate

    Retorna: A `PasswordVerificationResult` indicating success, success with rehash required, or failure.

  • propertyAlgorithm
    public PasswordHashAlgorithm Algorithm { get; }

    Gets the primary password hashing algorithm implemented by this instance.

  • propertyIsMemoryHard
    public static bool IsMemoryHard { get; }

    Gets a value indicating whether the underlying key derivation function is memory-hard.

  • propertySubstrateDescription
    public static string SubstrateDescription { get; }

    Gets the cryptographic substrate name backing this hasher.

  • fieldDefault
    public static readonly Argon2idPasswordHasher Default

    Gets the default singleton instance configured with 64 MB memory, 3 time-cost iterations, and 4 parallelism lanes.

  • fieldDefaultMaxAllowedMemoryCost
    public const int DefaultMaxAllowedMemoryCost

    Default maximum memory-cost parameter (in KiB) accepted in verification (64 MiB).

  • fieldMaxAllowedParallelism
    public const int MaxAllowedParallelism

    Maximum degree of parallelism accepted in verification.

  • fieldMaxAllowedTimeCost
    public const int MaxAllowedTimeCost

    Maximum time-cost iterations parameter accepted in verification.

  • fieldMinAllowedMemoryCost
    public const int MinAllowedMemoryCost

    Minimum memory-cost parameter (in KiB) accepted in verification (1 MiB).

  • fieldMinAllowedParallelism
    public const int MinAllowedParallelism

    Minimum degree of parallelism accepted in verification.

  • fieldMinAllowedTimeCost
    public const int MinAllowedTimeCost

    Minimum time-cost iterations parameter accepted in verification.

class

Pbkdf2PasswordHasher

Ensamblado: EricksonLopez.Security.Cryptography
public sealed class Pbkdf2PasswordHasher : IPasswordHasher
Implementa: IPasswordHasher

Provides password hashing using PBKDF2 (HMAC-SHA512) per format `PBKDF2.V1$<iterations>$<salt>$<hash>`, compatible with Native AOT and zero dependencies.

Notas:

Tier 1 — Direct Cryptographic Primitive: This hasher is part of `EricksonLopez.Security.Cryptography` and targets direct use in standalone cryptographic workflows. It uses 600,000 PBKDF2-HMAC-SHA512 iterations and the `PBKDF2.V1$` modular crypt prefix. Format incompatibility with Tier 2: The hash format produced by this hasher (`PBKDF2.V1$<iterations>$<salt>$<hash>`) is not interchangeable with the format produced by `EricksonLopez.Security.Passwords.Pbkdf2PasswordHasher` (`$pbkdf2-sha512$i=210000$s=<salt>$<hash>`). Mixing hashes from both classes in the same verification path will cause `PasswordVerificationResult.Failed`. See ADR-023 (Dual PBKDF2 Password Hasher Archetypes) for full rationale. Choosing the right hasher: - Use this hasher for direct cryptographic derivation workflows where hash format interop is not required. - Use `EricksonLopez.Security.Passwords.Pbkdf2PasswordHasher` (Tier 2) with `CompositePasswordHasher` for application password management with multi-algorithm migration support.

Miembros (6)

  • constructorPbkdf2PasswordHasher
    public Pbkdf2PasswordHasher(IConstantTimeComparer comparer, ICryptographicRandomNumberGenerator random)

    Initializes a new instance of the `Pbkdf2PasswordHasher` class with default iterations (600,000).

    comparer: IConstantTimeComparer
    The comparer for constant-time hash verification.
    random: ICryptographicRandomNumberGenerator
    The cryptographic random number generator for generating cryptographic salts.

    Exceptions: ArgumentNullException: `comparer` or `random` is `null`

  • methodHashPassword
    public string HashPassword(ReadOnlySpan<char> password)

    Computes a cryptographically salted and parameterized password hash for the specified password.

    password: ReadOnlySpan<char>
    The plaintext password character span. Must not exceed 256 characters.

    Retorna: A standardized, self-describing password hash string.

    Exceptions: ArgumentOutOfRangeException: `password` length exceeds 256 characters

  • methodNeedsRehash
    public bool NeedsRehash(string hashedPassword)

    Determines whether the given stored password hash requires rehashing due to parameter updates or algorithm evolution.

    hashedPassword: string
    The stored hash string to evaluate

    Retorna: `true` if the hash should be regenerated with current parameters; otherwise, `false`.

    Returns `true` if `hashedPassword` is null, empty, or whitespace (indicating an invalid hash that must be regenerated); returns `true` also if the format is invalid, matches Tier 2 format, or stored iterations are less than `600,000`. Returns `false` only when the hash is well-formed and meets current iteration requirements.

  • methodVerifyPassword
    public PasswordVerificationResult VerifyPassword(ReadOnlySpan<char> password, string hashedPassword)

    Verifies a plaintext password against a stored hashed password using constant-time evaluation.

    password: ReadOnlySpan<char>
    The candidate password character span to verify
    hashedPassword: string
    The stored hashed password string to evaluate

    Retorna: A `PasswordVerificationResult` indicating success, success with rehash required, or failure.

  • propertyAlgorithm
    public PasswordHashAlgorithm Algorithm { get; }

    Gets the password hashing algorithm implemented by this hasher (`PasswordHashAlgorithm.Pbkdf2HmacSha512`).

  • fieldDefaultIterations
    public const int DefaultIterations

    Defines the default number of PBKDF2 iterations (600,000) recommended by OWASP for SHA-512 password hashing.

EricksonLopez.Security.Cryptography.Pkcs11.Hsm#

1
class

Pkcs11SessionManager

Ensamblado: EricksonLopez.Security.Cryptography.Pkcs11
public sealed unsafe class Pkcs11SessionManager : IDisposable
Implementa: IDisposable

Encapsulates and manages the lifecycle of a PKCS#11 cryptographic session.

Notas:

Ensures proper session cleanup, releasing unmanaged session handles and performing HSM logout when disposed.

Miembros (4)

  • methodDispose
    public void Dispose()

    Inherits documentation from base type or interface.

  • methodLogin
    public Result Login(ReadOnlySpan<byte> pin)

    Authenticates a normal user to the HSM slot using the provided PIN bytes.

    pin: ReadOnlySpan<byte>
    The UTF-8 or raw byte sequence representing the user PIN.

    Retorna: A successful `Result` if authentication succeeds; otherwise, an error indicating login failure.

  • propertySessionId
    public CULong SessionId { get; }

    Gets the underlying unmanaged PKCS#11 session handle.

  • propertySyncLock
    public object SyncLock { get; }

    Gets the synchronization lock object for serializing operations across this session.

EricksonLopez.Security.Cryptography.Pkcs11.Signing#

2
class

Pkcs11DigitalSignatureEngine

Ensamblado: EricksonLopez.Security.Cryptography.Pkcs11
public sealed unsafe class Pkcs11DigitalSignatureEngine : IDigitalSignatureEngine
Implementa: IDigitalSignatureEngine

Provides hardware-backed digital signature generation and verification operations using PKCS#11.

Miembros (3)

  • constructorPkcs11DigitalSignatureEngine
    public Pkcs11DigitalSignatureEngine(Pkcs11SessionManager sessionManager)

    Initializes a new instance of the `Pkcs11DigitalSignatureEngine` class with the specified session manager.

    sessionManager: Pkcs11SessionManager
    The active PKCS#11 session manager.
  • methodSign
    public Result Sign(ReadOnlySpan<byte> payload, KeyIdentifier keyId, Span<byte> signatureDestination, out int bytesWritten)

    Signs the provided payload using the specified key.

    payload: ReadOnlySpan<byte>
    The data to sign.
    keyId: KeyIdentifier
    The identifier of the private key to use for signing.
    signatureDestination: Span<byte>
    The destination span for the generated signature.
    bytesWritten: out int
    The number of bytes written to the signature destination.

    Retorna: A `Result` indicating success or a cryptographic failure error.

  • methodVerify
    public Result Verify(ReadOnlySpan<byte> payload, ReadOnlySpan<byte> signature, KeyIdentifier keyId)

    Verifies the digital signature of the provided payload using the specified key.

    payload: ReadOnlySpan<byte>
    The data that was signed.
    signature: ReadOnlySpan<byte>
    The signature to verify.
    keyId: KeyIdentifier
    The identifier of the public key to use for verification.

    Retorna: A `Result` indicating whether the signature is valid.

class

Pkcs11SessionRsa

Ensamblado: EricksonLopez.Security.Cryptography.Pkcs11
public sealed class Pkcs11SessionRsa : RSA
Hereda de: RSA

Adapts a non-exportable PKCS#11 HSM private key handle to `RSA` so standard .NET JWT (`RsaSecurityKey`) and XMLDSig (`SignedXml`) pipelines can generate `RS256` signatures in hardware without exporting private key material.

Miembros (7)

  • constructorPkcs11SessionRsa
    public Pkcs11SessionRsa(Pkcs11SessionManager sessionManager, KeyIdentifier keyId, RSAParameters publicParameters)

    Initializes a new instance of the `Pkcs11SessionRsa` class.

    sessionManager: Pkcs11SessionManager
    The active PKCS#11 HSM session manager.
    keyId: KeyIdentifier
    The HSM private/public key label or numeric handle.
    publicParameters: RSAParameters
    The public RSA modulus and exponent corresponding to the HSM key.
  • methodExportParameters
    public override RSAParameters ExportParameters(bool includePrivateParameters)

    Inherits documentation from base type or interface.

    includePrivateParameters: bool
  • methodImportParameters
    public override void ImportParameters(RSAParameters parameters)

    Inherits documentation from base type or interface.

    parameters: RSAParameters
  • methodSignData
    public override byte[] SignData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)

    Inherits documentation from base type or interface.

    data: byte[]
    offset: int
    count: int
    hashAlgorithm: HashAlgorithmName
    padding: RSASignaturePadding
  • methodSignHash
    public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)

    Inherits documentation from base type or interface.

    hash: byte[]
    hashAlgorithm: HashAlgorithmName
    padding: RSASignaturePadding
  • methodVerifyData
    public override bool VerifyData(byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)

    Inherits documentation from base type or interface.

    data: byte[]
    offset: int
    count: int
    signature: byte[]
    hashAlgorithm: HashAlgorithmName
    padding: RSASignaturePadding
  • methodVerifyHash
    public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)

    Inherits documentation from base type or interface.

    hash: byte[]
    signature: byte[]
    hashAlgorithm: HashAlgorithmName
    padding: RSASignaturePadding

EricksonLopez.Security.Cryptography.Randomness#

2
class

ConstantTimeComparer

Ensamblado: EricksonLopez.Security.Cryptography
public sealed class ConstantTimeComparer : IConstantTimeComparer
Implementa: IConstantTimeComparer

Provides side-channel resistant constant-time comparisons over sensitive buffers.

Miembros (4)

  • methodFixedTimeEquals
    public bool FixedTimeEquals(ReadOnlySpan<byte> left, ReadOnlySpan<byte> right)

    Compares two byte spans for equality in execution time independent of data values, preventing side-channel timing attacks.

    left: ReadOnlySpan<byte>
    The left byte span.
    right: ReadOnlySpan<byte>
    The right byte span.

    Retorna: `true` if byte contents are identical and equal length; otherwise, `false`.

  • methodFixedTimeEquals
    public bool FixedTimeEquals(ReadOnlySpan<char> left, ReadOnlySpan<char> right)

    Compares two byte spans for equality in execution time independent of data values, preventing side-channel timing attacks.

    left: ReadOnlySpan<char>
    The left byte span.
    right: ReadOnlySpan<char>
    The right byte span.

    Retorna: `true` if byte contents are identical and equal length; otherwise, `false`.

  • methodFixedTimeEqualsSecure
    public bool FixedTimeEqualsSecure(ReadOnlySpan<byte> left, ReadOnlySpan<byte> right)

    Compares two character spans for equality in constant time, eliminating length-leakage side channels by hashing both inputs with a cryptographic digest before constant-time evaluation.

    left: ReadOnlySpan<byte>
    The left character span.
    right: ReadOnlySpan<byte>
    The right character span.

    Retorna: `true` if both spans are identical; otherwise, `false`.

  • methodFixedTimeEqualsSecure
    public bool FixedTimeEqualsSecure(ReadOnlySpan<char> left, ReadOnlySpan<char> right)

    Compares two character spans for equality in constant time, eliminating length-leakage side channels by hashing both inputs with a cryptographic digest before constant-time evaluation.

    left: ReadOnlySpan<char>
    The left character span.
    right: ReadOnlySpan<char>
    The right character span.

    Retorna: `true` if both spans are identical; otherwise, `false`.

class

CryptographicRandomNumberGenerator

Ensamblado: EricksonLopez.Security.Cryptography
public sealed class CryptographicRandomNumberGenerator : ICryptographicRandomNumberGenerator
Implementa: ICryptographicRandomNumberGenerator

Provides a cryptographically secure pseudo-random number generator (CSPRNG) implementation.

Miembros (3)

  • methodFill
    public void Fill(Span<byte> destination)

    Fills the destination byte span with cryptographically strong random bytes.

    destination: Span<byte>
    The destination span.
  • methodGetBytes
    public byte[] GetBytes(int count)

    Allocates and fills a byte array with cryptographically strong random bytes.

    count: int
    The number of bytes to generate.

    Retorna: A byte array containing cryptographically strong random bytes.

  • methodGetInt32
    public int GetInt32(int fromInclusive, int toExclusive)

    Generates a cryptographically strong random integer within the specified range.

    fromInclusive: int
    The inclusive lower bound.
    toExclusive: int
    The exclusive upper bound.

    Retorna: A cryptographically strong random integer within the specified range.

EricksonLopez.Security.Cryptography.XmlDSig#

7
interface

IXmlDigitalSignatureVerifier

Ensamblado: EricksonLopez.Security.Cryptography.XmlDSig
public interface IXmlDigitalSignatureVerifier

Defines capabilities for verifying W3C XML Digital Signatures (XMLDSig).

Miembros (5)

  • methodVerifyAndExtractSignedElement
    Result<XmlVerificationResult> VerifyAndExtractSignedElement(XmlDocument document, X509Certificate2? expectedCertificate = null, XmlVerificationOptions? options = null)

    Verifies the digital signature in an `XmlDocument` and extracts the cryptographically verified signed `XmlElement`, mitigating XML Signature Wrapping (XSW) attacks.

    document: XmlDocument
    The signed XML document.
    expectedCertificate: X509Certificate2?
    Optional expected certificate.
    options: XmlVerificationOptions?
    Optional verification options.

    Retorna: A result containing the `XmlVerificationResult` on success, or an error describing failure.

  • methodVerifyXml
    Result<bool> VerifyXml(string xmlContent, X509Certificate2? expectedCertificate = null)

    Verifies the digital signature in an XML string.

    xmlContent: string
    The signed XML content.
    expectedCertificate: X509Certificate2?
    Optional expected certificate. If omitted, uses embedded certificate in KeyInfo.

    Retorna: A successful result with `true` if signature is valid, or an error describing the verification failure.

  • methodVerifyXml
    Result<bool> VerifyXml(string xmlContent, X509Certificate2? expectedCertificate, XmlVerificationOptions? options)

    Verifies the digital signature in an XML string with custom verification options.

    xmlContent: string
    The signed XML content.
    expectedCertificate: X509Certificate2?
    Optional expected certificate.
    options: XmlVerificationOptions?
    Optional verification options.

    Retorna: A successful result with `true` if signature is valid, or an error describing the verification failure.

  • methodVerifyXml
    Result<bool> VerifyXml(XmlDocument document, X509Certificate2? expectedCertificate = null)

    Verifies the digital signature in an `XmlDocument`.

    document: XmlDocument
    The signed XML document.
    expectedCertificate: X509Certificate2?
    Optional expected certificate. If omitted, uses embedded certificate in KeyInfo.

    Retorna: A successful result with `true` if signature is valid, or an error describing the verification failure.

  • methodVerifyXml
    Result<bool> VerifyXml(XmlDocument document, X509Certificate2? expectedCertificate, XmlVerificationOptions? options)

    Verifies the digital signature in an `XmlDocument` with custom verification options.

    document: XmlDocument
    The signed XML document.
    expectedCertificate: X509Certificate2?
    Optional expected certificate.
    options: XmlVerificationOptions?
    Optional verification options.

    Retorna: A successful result with `true` if signature is valid, or an error describing the verification failure.

interface

IXmlDigitalSigner

Ensamblado: EricksonLopez.Security.Cryptography.XmlDSig
public interface IXmlDigitalSigner

Defines capabilities for generating W3C XML Digital Signatures (XMLDSig).

Miembros (2)

  • methodSignXml
    Result<string> SignXml(string xmlContent, X509Certificate2 certificate, XmlSigningOptions? options = null)

    Signs an XML string using the specified X.509 certificate and options, returning the signed XML string.

    xmlContent: string
    The raw XML content to sign.
    certificate: X509Certificate2
    The X.509 certificate containing an accessible RSA private key.
    options: XmlSigningOptions?
    Optional XML signing options.

    Retorna: A successful result containing the signed XML text, or an error describing the failure.

  • methodSignXml
    Result<XmlDocument> SignXml(XmlDocument document, X509Certificate2 certificate, XmlSigningOptions? options = null)

    Signs an `XmlDocument` in-place using the specified X.509 certificate and options.

    document: XmlDocument
    The XML document to sign.
    certificate: X509Certificate2
    The X.509 certificate containing an accessible RSA private key.
    options: XmlSigningOptions?
    Optional XML signing options.

    Retorna: A successful result containing the signed `XmlDocument`, or an error describing the failure.

class

XmlDigitalSignatureService

Ensamblado: EricksonLopez.Security.Cryptography.XmlDSig
public sealed class XmlDigitalSignatureService : IXmlDigitalSigner, IXmlDigitalSignatureVerifier
Implementa: IXmlDigitalSignatureVerifier, IXmlDigitalSigner

Provides W3C XML Digital Signature (XMLDSig) generation and verification operations.

Miembros (8)

  • methodSignXml
    public Result<string> SignXml(string xmlContent, X509Certificate2 certificate, XmlSigningOptions? options = null)

    Signs an XML string using the specified X.509 certificate and options, returning the signed XML string.

    xmlContent: string
    The raw XML content to sign.
    certificate: X509Certificate2
    The X.509 certificate containing an accessible RSA private key.
    options: XmlSigningOptions?
    Optional XML signing options.

    Retorna: A successful result containing the signed XML text, or an error describing the failure.

  • methodSignXml
    public Result<XmlDocument> SignXml(XmlDocument document, X509Certificate2 certificate, XmlSigningOptions? options = null)

    Signs an XML string using the specified X.509 certificate and options, returning the signed XML string.

    document: XmlDocument
    certificate: X509Certificate2
    The X.509 certificate containing an accessible RSA private key.
    options: XmlSigningOptions?
    Optional XML signing options.

    Retorna: A successful result containing the signed XML text, or an error describing the failure.

  • methodVerifyAndExtractSignedElement
    public Result<XmlVerificationResult> VerifyAndExtractSignedElement(XmlDocument document, X509Certificate2? expectedCertificate = null, XmlVerificationOptions? options = null)

    Verifies the digital signature in an `XmlDocument` and extracts the cryptographically verified signed `XmlElement`, mitigating XML Signature Wrapping (XSW) attacks.

    document: XmlDocument
    The signed XML document.
    expectedCertificate: X509Certificate2?
    Optional expected certificate.
    options: XmlVerificationOptions?
    Optional verification options.

    Retorna: A result containing the `XmlVerificationResult` on success, or an error describing failure.

  • methodVerifyXml
    public Result<bool> VerifyXml(string xmlContent, X509Certificate2? expectedCertificate = null)

    Verifies the digital signature in an XML string.

    xmlContent: string
    The signed XML content.
    expectedCertificate: X509Certificate2?
    Optional expected certificate. If omitted, uses embedded certificate in KeyInfo.

    Retorna: A successful result with `true` if signature is valid, or an error describing the verification failure.

  • methodVerifyXml
    public Result<bool> VerifyXml(string xmlContent, X509Certificate2? expectedCertificate, XmlVerificationOptions? options)

    Verifies the digital signature in an XML string with custom verification options.

    xmlContent: string
    The signed XML content.
    expectedCertificate: X509Certificate2?
    Optional expected certificate.
    options: XmlVerificationOptions?
    Optional verification options.

    Retorna: A successful result with `true` if signature is valid, or an error describing the verification failure.

  • methodVerifyXml
    public Result<bool> VerifyXml(XmlDocument document, X509Certificate2? expectedCertificate = null)

    Verifies the digital signature in an XML string.

    document: XmlDocument
    expectedCertificate: X509Certificate2?
    Optional expected certificate. If omitted, uses embedded certificate in KeyInfo.

    Retorna: A successful result with `true` if signature is valid, or an error describing the verification failure.

  • methodVerifyXml
    public Result<bool> VerifyXml(XmlDocument document, X509Certificate2? expectedCertificate, XmlVerificationOptions? options)

    Verifies the digital signature in an XML string with custom verification options.

    document: XmlDocument
    expectedCertificate: X509Certificate2?
    Optional expected certificate.
    options: XmlVerificationOptions?
    Optional verification options.

    Retorna: A successful result with `true` if signature is valid, or an error describing the verification failure.

  • fieldInstance
    public static readonly XmlDigitalSignatureService Instance

    Gets the default shared singleton instance of `XmlDigitalSignatureService`.

class

XmlSignatureCertificateExtractor

Ensamblado: EricksonLopez.Security.Cryptography.XmlDSig
public static class XmlSignatureCertificateExtractor

Provides utility methods for extracting embedded X.509 certificates from XML Digital Signatures (<Signature> elements).

Miembros (2)

  • methodExtractCertificate
    public static Result<X509Certificate2> ExtractCertificate(string xmlContent)

    Extracts the first embedded `X509Certificate2` from an XML string containing an XMLDSig signature.

    xmlContent: string
    The raw XML content.

    Retorna: A successful result containing the certificate, or an error if missing or invalid.

  • methodExtractCertificate
    public static Result<X509Certificate2> ExtractCertificate(XmlDocument document)

    Extracts the first embedded `X509Certificate2` from an `XmlDocument` containing an XMLDSig signature.

    document: XmlDocument
    The XML document.

    Retorna: A successful result containing the certificate, or an error if missing or invalid.

    Exceptions: ArgumentNullException: `document` is `null`

class

XmlSigningOptions

Ensamblado: EricksonLopez.Security.Cryptography.XmlDSig
public sealed class XmlSigningOptions

Specifies configuration options for W3C XML Digital Signature (XMLDSig) generation.

Miembros (9)

  • propertyCanonicalizationMethod
    public string CanonicalizationMethod { get; set; }

    Gets or sets the URI of the canonicalization method algorithm. Default is C14N 1.0 (`http://www.w3.org/TR/2001/REC-xml-c14n-20010315`).

    Exceptions: ArgumentException: The specified URI is not in `AllowedCanonicalizationMethods`

  • propertyDigestMethod
    public string DigestMethod { get; set; }

    Gets or sets the URI of the reference digest method algorithm. Default is SHA256 (`http://www.w3.org/2001/04/xmlenc#sha256`). SHA-1 and MD5 digests are not permitted.

    Exceptions: ArgumentException: The specified URI is not in `AllowedDigestMethods`

  • propertyIncludeKeyInfo
    public bool IncludeKeyInfo { get; set; }

    Gets or sets a value indicating whether to embed the public X.509 certificate in the <KeyInfo> element. Default is `true`.

  • propertyMaxCharactersInDocument
    public long MaxCharactersInDocument { get; set; }

    Gets or sets the maximum number of characters allowed in the XML document to prevent memory exhaustion DoS attacks. Default is 10,000,000 characters.

  • propertyReferenceUri
    public string ReferenceUri { get; set; }

    Gets or sets the reference URI pointing to the signed element. Default is empty string (""), indicating the entire containing document.

  • propertySignatureMethod
    public string SignatureMethod { get; set; }

    Gets or sets the URI of the signature method algorithm. Default is RSA-SHA256 (`http://www.w3.org/2001/04/xmldsig-more#rsa-sha256`). SHA-1 based methods are not permitted.

    Exceptions: ArgumentException: The specified URI is not in `AllowedSignatureMethods`

  • fieldAllowedCanonicalizationMethods
    public static readonly IReadOnlySet<string> AllowedCanonicalizationMethods

    Gets the set of permitted canonicalization method URIs. Attempts to set a URI not in this list will throw `ArgumentException`.

  • fieldAllowedDigestMethods
    public static readonly IReadOnlySet<string> AllowedDigestMethods

    Gets the set of permitted digest method algorithm URIs. Attempts to set a URI not in this list will throw `ArgumentException`. SHA-1 and MD5 digests are intentionally excluded.

  • fieldAllowedSignatureMethods
    public static readonly IReadOnlySet<string> AllowedSignatureMethods

    Gets the set of permitted signature method algorithm URIs. Attempts to set a URI not in this list will throw `ArgumentException`. SHA-1 based methods are intentionally excluded.

class

XmlVerificationOptions

Ensamblado: EricksonLopez.Security.Cryptography.XmlDSig
public sealed class XmlVerificationOptions

Specifies configuration options for verifying W3C XML Digital Signatures (XMLDSig).

Miembros (10)

  • propertyAllowDuplicateIds
    public bool AllowDuplicateIds { get; set; }

    Gets or sets a value indicating whether duplicate ID attributes are permitted in the XML document.

    When `false` (the default, secure setting), documents with duplicate ID attributes are rejected with a validation error to prevent XML Signature Wrapping (XSW) and element confusion attacks.

  • propertyAllowMultipleSignatures
    public bool AllowMultipleSignatures { get; set; }

    Gets or sets a value indicating whether to allow documents containing multiple <Signature> elements.

    When `false` (the default, secure setting), XML documents with more than one `<Signature>` element are rejected with a validation error. This prevents XML Signature Wrapping (XSW) and signature selection ambiguity attacks where an untrusted signature wraps or precedes an authentic signature. Set to `true` only if multi-signature documents are explicitly expected and handled.

  • propertyAllowedDigestMethods
    public ISet<string> AllowedDigestMethods { get; set; }

    Gets or sets the set of allowed XMLDSig digest method URIs. Insecure algorithms like SHA-1 and MD5 are rejected by default.

  • propertyAllowedSignatureMethods
    public ISet<string> AllowedSignatureMethods { get; set; }

    Gets or sets the set of allowed XMLDSig signature method URIs. Insecure algorithms like SHA-1 and MD5 are rejected by default.

  • propertyAllowedTransformAlgorithms
    public ISet<string> AllowedTransformAlgorithms { get; set; }

    Gets or sets the set of allowed XMLDSig transform algorithm URIs. By default, dangerous transforms like XSLT or XPath are rejected to prevent remote code execution and DoS.

  • propertyCertificateTrustEvaluator
    public Func<X509Certificate2, bool>? CertificateTrustEvaluator { get; set; }

    Gets or sets a custom certificate trust evaluator predicate.

  • propertyCustomTrustAnchors
    public IList<X509Certificate2> CustomTrustAnchors { get; set; }

    Gets or sets a collection of custom trusted root certificates for evaluating embedded certificates.

  • propertyMaxCharactersInDocument
    public long MaxCharactersInDocument { get; set; }

    Gets or sets the maximum number of characters allowed in the XML document to prevent memory exhaustion DoS attacks. Default is 10,000,000 characters.

  • propertyRequireRootElementCoverage
    public bool RequireRootElementCoverage { get; set; }

    Gets or sets a value indicating whether the XML digital signature must cover the root element of the document. When true (the default), subtree signatures that do not cover the document root are rejected to prevent partial document tampering.

  • propertyRequireTrustedCertificate
    public bool RequireTrustedCertificate { get; set; }

    Gets or sets a value indicating whether embedded certificates in KeyInfo must be validated against a trusted chain or root anchor.

class

XmlVerificationResult

Ensamblado: EricksonLopez.Security.Cryptography.XmlDSig
public sealed class XmlVerificationResult

Encapsulates the verified XML element, reference URI, and signing certificate resulting from a successful cryptographic XML signature validation. Protects against XML Signature Wrapping (XSW) attacks by binding the verified element.

Miembros (5)

  • constructorXmlVerificationResult
    public XmlVerificationResult(bool isValid, XmlElement? signedElement, string? referenceUri, X509Certificate2? signingCertificate)

    Initializes a new instance of the `XmlVerificationResult` class.

    isValid: bool
    A value indicating whether cryptographic signature verification succeeded
    signedElement: XmlElement?
    The verified XML element from the signature manifest
    referenceUri: string?
    The signature reference URI
    signingCertificate: X509Certificate2?
    The certificate that verified the signature
  • propertyIsValid
    public bool IsValid { get; }

    Gets a value indicating whether cryptographic signature verification succeeded.

  • propertyReferenceUri
    public string? ReferenceUri { get; }

    Gets the signature reference URI (e.g. "" for whole document, or "#elementId").

  • propertySignedElement
    public XmlElement? SignedElement { get; }

    Gets the verified `XmlElement` that was actually signed in the signature manifest. Consumers must process this element rather than untrusted sibling or parent nodes to prevent XSW attacks.

  • propertySigningCertificate
    public X509Certificate2? SigningCertificate { get; }

    Gets the certificate that verified the signature, if available.

EricksonLopez.Security.Diagnostics#

2
class

SecurityActivitySource

Ensamblado: EricksonLopez.Security
public static class SecurityActivitySource

Provides the central `Diagnostics.ActivitySource` for all EricksonLopez.Security telemetry. Consumers opt in by subscribing to this source via an ActivityListener or via the optional `EricksonLopez.Security.OpenTelemetry` satellite package.

Notas:

Per ADR-019, `SecurityActivitySource` resides in the core package and uses exclusively `System.Diagnostics` from the BCL inbox assembly — no OTel SDK dependency is introduced here.

Miembros (16)

  • fieldDecryptOperation
    public const string DecryptOperation

    Defines the AEAD decryption span name.

  • fieldEncryptOperation
    public const string EncryptOperation

    Defines the AEAD encryption span name.

  • fieldHashPasswordOperation
    public const string HashPasswordOperation

    Defines the password hashing span name.

  • fieldInstance
    public static readonly ActivitySource Instance

    Provides the shared `ActivitySource` emitting all security operation spans.

  • fieldProtectSecretOperation
    public const string ProtectSecretOperation

    Defines the secret protection (wrap) span name.

  • fieldSourceName
    public const string SourceName

    Specifies the canonical source name used when subscribing via `ActivityListener`.

  • fieldSourceVersion
    public const string SourceVersion

    Specifies the semantic version of this instrumentation.

  • fieldTagAlgorithm
    public const string TagAlgorithm

    Defines the tag key for the AEAD algorithm name (e.g. "aes-256-gcm").

  • fieldTagErrorCode
    public const string TagErrorCode

    Defines the tag key for the error code when an operation fails (e.g. "KeyExpired", "DecryptionFailed").

  • fieldTagHashAlgorithm
    public const string TagHashAlgorithm

    Defines the tag key for the password hashing algorithm (e.g. "argon2id", "pbkdf2-sha512").

  • fieldTagKeyVersion
    public const string TagKeyVersion

    Defines the tag key for the key version (e.g. "v2").

  • fieldTagResult
    public const string TagResult

    Defines the tag key for the operation result: "success", "failure", "rehash_needed".

  • fieldUnprotectSecretOperation
    public const string UnprotectSecretOperation

    Defines the secret unprotection (unwrap) span name.

  • fieldUnwrapKeyOperation
    public const string UnwrapKeyOperation

    Defines the key unwrap (KMS) span name.

  • fieldVerifyPasswordOperation
    public const string VerifyPasswordOperation

    Defines the password verification span name.

  • fieldWrapKeyOperation
    public const string WrapKeyOperation

    Defines the key wrap (KMS) span name.

class

SecurityMeter

Ensamblado: EricksonLopez.Security
public static class SecurityMeter

Provides the central `Metrics.Meter` for all EricksonLopez.Security metrics. Consumers subscribe via `MeterListener` or via the optional `EricksonLopez.Security.OpenTelemetry` satellite package which auto-registers this meter.

Notas:

Per ADR-019, uses only `System.Diagnostics.Metrics` from the BCL inbox assembly (.NET 6+). No OTel SDK dependency. Fully Native AOT compatible.

Miembros (11)

  • fieldApiKeyValidationsTotal
    public static readonly Counter<long> ApiKeyValidationsTotal

    Gets a counter for the total number of API key validation attempts. Tags: `security.result` = "success" | "invalid" | "expired" | "revoked".

  • fieldDecryptTotal
    public static readonly Counter<long> DecryptTotal

    Gets a counter for the total number of successful AEAD decrypt operations. Tags: `security.algorithm`, `security.key.version`.

  • fieldEncryptTotal
    public static readonly Counter<long> EncryptTotal

    Gets a counter for the total number of successful AEAD encrypt operations. Tags: `security.algorithm` (e.g. "aes-256-gcm").

  • fieldInstance
    public static readonly Meter Instance

    Provides the shared `Meter` instance.

  • fieldKeyDestructionsTotal
    public static readonly Counter<long> KeyDestructionsTotal

    Gets a counter for the total number of permanent key destruction events. Tags: `security.key.version`, `security.result` (e.g. "success", "failed").

  • fieldKeyRevocationsTotal
    public static readonly Counter<long> KeyRevocationsTotal

    Gets a counter for the total number of key revocation events. Tags: `security.key.version`, `security.result` (e.g. "success", "already_revoked").

  • fieldKeyRotationsTotal
    public static readonly Counter<long> KeyRotationsTotal

    Gets a counter for the total number of key rotation events. Tags: `security.key.version` (the new version).

  • fieldLegacyPbkdf2HashingDurationMs
    public static readonly Histogram<double> LegacyPbkdf2HashingDurationMs

    Gets a histogram measuring the duration of `LegacyPbkdf2PasswordHasher` password hashing operations in milliseconds. This is the primary latency signal for password security tuning.

    v1.x substrate: `LegacyPbkdf2PasswordHasher` uses PBKDF2-HMAC-SHA512 internally (effective iterations = `time_cost × 70,000`). Latency values measured by this histogram reflect PBKDF2 execution time, not RFC 9106 Argon2id memory-hard hashing. Use this data to tune `LegacyPbkdf2PasswordHasher(iterations)` to achieve your target hash duration (300–500 ms recommended). See ADR-024.

  • fieldMeterName
    public const string MeterName

    Specifies the canonical meter name used when subscribing via `MeterListener`.

  • fieldPasswordVerificationsTotal
    public static readonly Counter<long> PasswordVerificationsTotal

    Gets a counter for the total number of password verification attempts. Tags: `security.result` = "success" | "rehash_needed" | "failure". `security.hash.algorithm` = "argon2id" | "pbkdf2-sha512".

  • fieldPbkdf2HashingDurationMs
    public static readonly Histogram<double> Pbkdf2HashingDurationMs

    Gets a histogram measuring the duration of PBKDF2 password hashing operations in milliseconds.

EricksonLopez.Security.GoogleCloud#

4
class

GoogleCloudKmsKeyStore

Ensamblado: EricksonLopez.Security.GoogleCloud
public sealed class GoogleCloudKmsKeyStore : IKeyStore, IDisposable
Implementa: IDisposable, IKeyStore

Provides an `IKeyStore` adapter backed by Google Cloud KMS and Secret Manager. Supports Cloud HSM hardware-protected keys for workloads such as high-assurance digital signing.

Notas:

Connects directly to Google Cloud services using `KeyManagementServiceClient` and `SecretManagerServiceClient`.

Miembros (8)

  • constructorGoogleCloudKmsKeyStore
    public GoogleCloudKmsKeyStore(IOptions<GoogleCloudSecurityOptions> options)

    Initializes a new instance of the `GoogleCloudKmsKeyStore` class with default null logger.

    options: IOptions<GoogleCloudSecurityOptions>
    The Google Cloud security options.
  • constructorGoogleCloudKmsKeyStore
    public GoogleCloudKmsKeyStore(IOptions<GoogleCloudSecurityOptions> options, ILogger<GoogleCloudKmsKeyStore> logger, TimeProvider? timeProvider = null)

    Initializes a new instance of the `GoogleCloudKmsKeyStore` class.

    options: IOptions<GoogleCloudSecurityOptions>
    The Google Cloud security options.
    logger: ILogger<GoogleCloudKmsKeyStore>
    The logger for diagnostics and operational warnings.
    timeProvider: TimeProvider?
    Optional time provider (defaults to `TimeProvider.System`).

    Exceptions: ArgumentNullException: `options` or `logger` is `null`; InvalidOperationException: Options lack ProjectId and pre-configured clients

  • constructorGoogleCloudKmsKeyStore
    public GoogleCloudKmsKeyStore(KeyManagementServiceClient? kmsClient, SecretManagerServiceClient secretClient, IOptions<GoogleCloudSecurityOptions> options, ILogger<GoogleCloudKmsKeyStore>? logger = null, TimeProvider? timeProvider = null)

    Initializes a new instance of the `GoogleCloudKmsKeyStore` class using pre-configured clients.

    kmsClient: KeyManagementServiceClient?
    Optional pre-configured KMS client for envelope encryption.
    secretClient: SecretManagerServiceClient
    The Google Cloud Secret Manager client.
    options: IOptions<GoogleCloudSecurityOptions>
    The Google Cloud security options.
    logger: ILogger<GoogleCloudKmsKeyStore>?
    Optional logger for diagnostics.
    timeProvider: TimeProvider?
    Optional time provider (defaults to `TimeProvider.System`).
  • methodDispose
    public void Dispose()

    Releases the resources used by this instance.

  • methodGetKeyAsync
    public async ValueTask<Result<CryptographicKey>> GetKeyAsync(KeyIdentifier keyId, KeyVersion version, CancellationToken cancellationToken = default)

    Retrieves a cryptographic key by identifier and version.

    keyId: KeyIdentifier
    The key identifier.
    version: KeyVersion
    The key version.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the `CryptographicKey`.

  • methodListMetadataAsync
    public async ValueTask<Result<IReadOnlyList<KeyMetadata>>> ListMetadataAsync(KeyPurpose? purpose = null, CancellationToken cancellationToken = default)

    Retrieves all key metadata stored in the repository.

    purpose: KeyPurpose?
    Optional purpose filter.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a result with a list of key metadata records.

  • methodSaveKeyAsync
    public async ValueTask<Result> SaveKeyAsync(CryptographicKey key, CancellationToken cancellationToken = default)

    Persists a new cryptographic key into the key store.

    key: CryptographicKey
    The cryptographic key to save.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating success or failure.

  • methodUpdateStatusAsync
    public async ValueTask<Result> UpdateStatusAsync(KeyIdentifier keyId, KeyVersion version, KeyStatus newStatus, CancellationToken cancellationToken = default)

    Updates the lifecycle status of a specific key.

    keyId: KeyIdentifier
    The key identifier.
    version: KeyVersion
    The key version.
    newStatus: KeyStatus
    The new lifecycle status.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating the outcome.

class

GoogleCloudKmsKeyWrappingProvider

Ensamblado: EricksonLopez.Security.GoogleCloud
public sealed class GoogleCloudKmsKeyWrappingProvider : IKmsKeyWrappingProvider
Implementa: IKmsKeyWrappingProvider

Provides an `IKmsKeyWrappingProvider` backed by Google Cloud KMS (including Cloud HSM) using `KeyManagementServiceClient.EncryptAsync(EncryptRequest, CallSettings)` and `KeyManagementServiceClient.DecryptAsync(DecryptRequest, CallSettings)` with `AdditionalAuthenticatedData` binding.

Miembros (5)

  • constructorGoogleCloudKmsKeyWrappingProvider
    public GoogleCloudKmsKeyWrappingProvider(IOptions<GoogleCloudSecurityOptions> options)

    Initializes a new instance of the `GoogleCloudKmsKeyWrappingProvider` class with default null logger.

    options: IOptions<GoogleCloudSecurityOptions>
    The Google Cloud security options.
  • constructorGoogleCloudKmsKeyWrappingProvider
    public GoogleCloudKmsKeyWrappingProvider(IOptions<GoogleCloudSecurityOptions> options, ILogger<GoogleCloudKmsKeyWrappingProvider> logger)

    Initializes a new instance of the `GoogleCloudKmsKeyWrappingProvider` class.

    options: IOptions<GoogleCloudSecurityOptions>
    The Google Cloud security options.
    logger: ILogger<GoogleCloudKmsKeyWrappingProvider>
    The structured logger.

    Exceptions: ArgumentNullException: `options` or `logger` is `null`.; InvalidOperationException: Neither `GoogleCloudSecurityOptions.KmsClient` nor `GoogleCloudSecurityOptions.ProjectId` is configured.

  • constructorGoogleCloudKmsKeyWrappingProvider
    public GoogleCloudKmsKeyWrappingProvider(KeyManagementServiceClient kmsClient, IOptions<GoogleCloudSecurityOptions> options, ILogger<GoogleCloudKmsKeyWrappingProvider>? logger = null)

    Initializes a new instance of the `GoogleCloudKmsKeyWrappingProvider` class using a pre-configured KMS client.

    kmsClient: KeyManagementServiceClient
    The Google Cloud KMS client.
    options: IOptions<GoogleCloudSecurityOptions>
    The Google Cloud security options.
    logger: ILogger<GoogleCloudKmsKeyWrappingProvider>?
    Optional structured logger.

    Exceptions: ArgumentNullException: `kmsClient` or `options` is `null`.

  • methodUnwrapKeyAsync
    public async ValueTask<Result<ISecretBuffer>> UnwrapKeyAsync(ReadOnlyMemory<byte> wrappedKey, ReadOnlyMemory<byte> associatedData = default, CancellationToken cancellationToken = default)

    Decrypts (unwraps) previously wrapped key material into a deterministic memory-scrubbing `ISecretBuffer`.

    wrappedKey: ReadOnlyMemory<byte>
    The wrapped key ciphertext bytes produced by `WrapKeyAsync`.
    associatedData: ReadOnlyMemory<byte>
    Optional authenticated associated data that must match the AAD used when wrapping.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A `Result<T>` containing a disposable `ISecretBuffer` whose memory is zeroed on disposal, or a typed security error.

  • methodWrapKeyAsync
    public async ValueTask<Result<byte[]>> WrapKeyAsync(ReadOnlyMemory<byte> plaintextKey, ReadOnlyMemory<byte> associatedData = default, CancellationToken cancellationToken = default)

    Encrypts (wraps) raw Data Encryption Key (DEK) or PKCS#8 asymmetric private key material under the configured KEK.

    plaintextKey: ReadOnlyMemory<byte>
    The raw key material to wrap. Must not be empty.
    associatedData: ReadOnlyMemory<byte>
    Optional authenticated associated data (for example, key identifier or tenant binding) bound to the wrapped key.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A `Result<T>` containing the opaque wrapped key ciphertext bytes on success, or a typed security error.

class

GoogleCloudSecretManagerStore

Ensamblado: EricksonLopez.Security.GoogleCloud
public sealed class GoogleCloudSecretManagerStore : ISecretStore
Implementa: ISecretStore

Provides an `ISecretStore` adapter backed by Google Cloud Secret Manager.

Notas:

Connects directly to Google Cloud Secret Manager using `SecretManagerServiceClient`.

Miembros (5)

  • constructorGoogleCloudSecretManagerStore
    public GoogleCloudSecretManagerStore(IOptions<GoogleCloudSecurityOptions> options)

    Initializes a new instance of the `GoogleCloudSecretManagerStore` class with default null logger.

    options: IOptions<GoogleCloudSecurityOptions>
    The Google Cloud security options.
  • constructorGoogleCloudSecretManagerStore
    public GoogleCloudSecretManagerStore(IOptions<GoogleCloudSecurityOptions> options, ILogger<GoogleCloudSecretManagerStore> logger)

    Initializes a new instance of the `GoogleCloudSecretManagerStore` class.

    options: IOptions<GoogleCloudSecurityOptions>
    The Google Cloud security options.
    logger: ILogger<GoogleCloudSecretManagerStore>
    The logger for diagnostics and operational warnings.

    Exceptions: ArgumentNullException: `options` or `logger` is `null`; InvalidOperationException: Neither ProjectId nor pre-configured SecretManagerClient is provided

  • constructorGoogleCloudSecretManagerStore
    public GoogleCloudSecretManagerStore(SecretManagerServiceClient client, IOptions<GoogleCloudSecurityOptions> options, ILogger<GoogleCloudSecretManagerStore>? logger = null)

    Initializes a new instance of the `GoogleCloudSecretManagerStore` class using a pre-configured client.

    client: SecretManagerServiceClient
    The pre-configured Secret Manager client.
    options: IOptions<GoogleCloudSecurityOptions>
    The Google Cloud security options.
    logger: ILogger<GoogleCloudSecretManagerStore>?
    Optional logger for diagnostics.
  • methodGetSecretAsync
    public async ValueTask<Result<Redacted<string>>> GetSecretAsync(string secretName, CancellationToken cancellationToken = default)

    Retrieves a secret by name as a memory-safe `Redacted<T>` string container.

    secretName: string
    The unique secret key name.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the secret value.

  • methodSetSecretAsync
    public async ValueTask<Result> SetSecretAsync(string secretName, string secretValue, CancellationToken cancellationToken = default)

    Sets or updates a secret in the underlying store.

    secretName: string
    The unique secret key name.
    secretValue: string
    The secret value to persist.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating success or failure.

class

GoogleCloudSecurityOptions

Ensamblado: EricksonLopez.Security.GoogleCloud
public sealed class GoogleCloudSecurityOptions

Specifies configuration options for connecting to Google Cloud KMS (including Cloud HSM) and Secret Manager.

Miembros (8)

  • propertyCryptoKeyId
    public string? CryptoKeyId { get; set; }

    Gets or sets an alias for `KmsCryptoKeyId` for configuration convenience.

  • propertyKeyRingId
    public string? KeyRingId { get; set; }

    Gets or sets the default Google Cloud KMS KeyRing ID (e.g. "signing-keys" or "app-keys").

  • propertyKmsClient
    public Google.Cloud.Kms.V1.KeyManagementServiceClient? KmsClient { get; set; }

    Gets or sets an explicit pre-configured `V1.KeyManagementServiceClient` instance.

    When set, this instance takes precedence over creating a new client.

  • propertyKmsCryptoKeyId
    public string? KmsCryptoKeyId { get; set; }

    Gets or sets the Google Cloud KMS CryptoKey ID for envelope encryption of keys stored in Secret Manager.

  • propertyLocationId
    public string LocationId { get; set; }

    Gets or sets the Google Cloud KMS location identifier (default: "global", or specific region such as "us-east1").

  • propertyProjectId
    public string? ProjectId { get; set; }

    Gets or sets the Google Cloud project identifier (e.g. "acme-security-prod" or "enterprise-kms-prod").

  • propertySecretManagerClient
    public Google.Cloud.SecretManager.V1.SecretManagerServiceClient? SecretManagerClient { get; set; }

    Gets or sets an explicit pre-configured `V1.SecretManagerServiceClient` instance.

    When set, this instance takes precedence over creating a new client.

  • propertySecretPrefix
    public string SecretPrefix { get; set; }

    Gets or sets an optional prefix for secret names in Google Cloud Secret Manager for namespace isolation.

EricksonLopez.Security.HashiCorpVault#

3
class

HashiCorpVaultKeyStore

Ensamblado: EricksonLopez.Security.HashiCorpVault
public sealed class HashiCorpVaultKeyStore : IKeyStore, IDisposable
Implementa: IDisposable, IKeyStore

Provides an `IKeyStore` adapter backed by HashiCorp Vault Transit and KV v2 cryptographic keys.

Notas:

Connects directly to HashiCorp Vault HTTP API using AppRole or Token authentication. Keys and associated lifecycle metadata are persisted durably and securely in Vault KV v2 storage.

Miembros (7)

  • constructorHashiCorpVaultKeyStore
    public HashiCorpVaultKeyStore(IOptions<HashiCorpVaultOptions> options)

    Initializes a new instance of the `HashiCorpVaultKeyStore` class with default null logger.

    options: IOptions<HashiCorpVaultOptions>
    The HashiCorp Vault options.
  • constructorHashiCorpVaultKeyStore
    public HashiCorpVaultKeyStore(IOptions<HashiCorpVaultOptions> options, ILogger<HashiCorpVaultKeyStore> logger)

    Initializes a new instance of the `HashiCorpVaultKeyStore` class.

    options: IOptions<HashiCorpVaultOptions>
    The HashiCorp Vault options.
    logger: ILogger<HashiCorpVaultKeyStore>
    The logger for diagnostics and operational warnings.

    Exceptions: ArgumentNullException: `options` or `logger` is `null`; InvalidOperationException: Options are invalid or missing required Vault URL

  • methodDispose
    public void Dispose()

    Releases the resources used by this instance.

  • methodGetKeyAsync
    public async ValueTask<Result<CryptographicKey>> GetKeyAsync(KeyIdentifier keyId, KeyVersion version, CancellationToken cancellationToken = default)

    Retrieves a cryptographic key by identifier and version.

    keyId: KeyIdentifier
    The key identifier.
    version: KeyVersion
    The key version.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the `CryptographicKey`.

  • methodListMetadataAsync
    public async ValueTask<Result<IReadOnlyList<KeyMetadata>>> ListMetadataAsync(KeyPurpose? purpose = null, CancellationToken cancellationToken = default)

    Retrieves all key metadata stored in the repository.

    purpose: KeyPurpose?
    Optional purpose filter.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a result with a list of key metadata records.

  • methodSaveKeyAsync
    public async ValueTask<Result> SaveKeyAsync(CryptographicKey key, CancellationToken cancellationToken = default)

    Persists a new cryptographic key into the key store.

    key: CryptographicKey
    The cryptographic key to save.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating success or failure.

  • methodUpdateStatusAsync
    public async ValueTask<Result> UpdateStatusAsync(KeyIdentifier keyId, KeyVersion version, KeyStatus newStatus, CancellationToken cancellationToken = default)

    Updates the lifecycle status of a specific key.

    keyId: KeyIdentifier
    The key identifier.
    version: KeyVersion
    The key version.
    newStatus: KeyStatus
    The new lifecycle status.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating the outcome.

class

HashiCorpVaultOptions

Ensamblado: EricksonLopez.Security.HashiCorpVault
public sealed class HashiCorpVaultOptions

Specifies configuration options for connecting to HashiCorp Vault.

Miembros (10)

  • propertyAppRoleMountPath
    public string AppRoleMountPath { get; set; }

    Gets or sets the mount path for AppRole authentication (default: "approle").

  • propertyHttpClient
    public System.Net.Http.HttpClient? HttpClient { get; set; }

    Gets or sets an optional pre-configured `Http.HttpClient` instance (e.g., configured with mTLS certificates).

  • propertyKvMountPath
    public string KvMountPath { get; set; }

    Gets or sets the KV v2 secrets engine mount path (default: "secret").

  • propertyNamespace
    public string? Namespace { get; set; }

    Gets or sets an optional Vault Enterprise namespace (sent in the X-Vault-Namespace header).

  • propertyRoleId
    public string? RoleId { get; set; }

    Gets or sets the AppRole Role ID for automated enterprise service authentication.

  • propertySecretId
    public string? SecretId { get; set; }

    Gets or sets the AppRole Secret ID for automated enterprise service authentication.

  • propertySecretPathPrefix
    public string SecretPathPrefix { get; set; }

    Gets or sets the optional path prefix for secret names.

  • propertyToken
    public string? Token { get; set; }

    Gets or sets the static Vault authentication token (sent in the X-Vault-Token header).

  • propertyTransitMountPath
    public string TransitMountPath { get; set; }

    Gets or sets the Transit secrets engine mount path (default: "transit").

  • propertyVaultUrl
    public Uri? VaultUrl { get; set; }

    Gets or sets the Vault server URL (e.g. "https://vault.internal:8200/").

class

HashiCorpVaultSecretStore

Ensamblado: EricksonLopez.Security.HashiCorpVault
public sealed class HashiCorpVaultSecretStore : ISecretStore, IDisposable
Implementa: IDisposable, ISecretStore

Provides an `ISecretStore` adapter backed by the HashiCorp Vault KV v2 secrets engine.

Notas:

Connects directly to HashiCorp Vault HTTP API using AppRole or Token authentication. Validates all secret names to prevent directory traversal and unauthorized path injection.

Miembros (5)

  • constructorHashiCorpVaultSecretStore
    public HashiCorpVaultSecretStore(IOptions<HashiCorpVaultOptions> options)

    Initializes a new instance of the `HashiCorpVaultSecretStore` class with default null logger.

    options: IOptions<HashiCorpVaultOptions>
    The HashiCorp Vault options.
  • constructorHashiCorpVaultSecretStore
    public HashiCorpVaultSecretStore(IOptions<HashiCorpVaultOptions> options, ILogger<HashiCorpVaultSecretStore> logger)

    Initializes a new instance of the `HashiCorpVaultSecretStore` class.

    options: IOptions<HashiCorpVaultOptions>
    The HashiCorp Vault options.
    logger: ILogger<HashiCorpVaultSecretStore>
    The logger for diagnostics and operational warnings.

    Exceptions: ArgumentNullException: `options` or `logger` is `null`; InvalidOperationException: Options are invalid or missing required Vault URL

  • methodDispose
    public void Dispose()

    Releases the resources used by this instance.

  • methodGetSecretAsync
    public async ValueTask<Result<Redacted<string>>> GetSecretAsync(string secretName, CancellationToken cancellationToken = default)

    Retrieves a secret by name as a memory-safe `Redacted<T>` string container.

    secretName: string
    The unique secret key name.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the secret value.

  • methodSetSecretAsync
    public async ValueTask<Result> SetSecretAsync(string secretName, string secretValue, CancellationToken cancellationToken = default)

    Sets or updates a secret in the underlying store.

    secretName: string
    The unique secret key name.
    secretValue: string
    The secret value to persist.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating success or failure.

EricksonLopez.Security.KeyManagement#

11
class

DelegateKeyRevocationNotifier

Ensamblado: EricksonLopez.Security
public sealed class DelegateKeyRevocationNotifier : IKeyRevocationNotifier
Implementa: IKeyRevocationNotifier

Provides a distributed-ready adapter for `IKeyRevocationNotifier` that forwards key revocation broadcasts to an external message broker or distributed cache (such as Redis Pub/Sub, RabbitMQ, Kafka, or Azure Service Bus) while coordinating local in-process notification across active `IKeyRing` instances.

Miembros (4)

  • constructorDelegateKeyRevocationNotifier
    public DelegateKeyRevocationNotifier(Func<KeyIdentifier, KeyVersion, KeyPurpose, CancellationToken, ValueTask> publishHandler)

    Initializes a new instance of the `DelegateKeyRevocationNotifier` class.

    publishHandler: Func<KeyIdentifier, KeyVersion, KeyPurpose, CancellationToken, ValueTask>
    The asynchronous delegate invoked to broadcast key revocation events to an external message broker.

    Exceptions: ArgumentNullException: `publishHandler` is `null`

  • methodNotifyRevokedAsync
    public async ValueTask NotifyRevokedAsync(KeyIdentifier keyId, KeyVersion version, KeyPurpose purpose, CancellationToken cancellationToken = default)

    Broadcasts a key revocation notification to all registered listeners.

    keyId: KeyIdentifier
    The identifier of the revoked key.
    version: KeyVersion
    The version of the revoked key.
    purpose: KeyPurpose
    The purpose of the revoked key.
    cancellationToken: CancellationToken
    A token to observe while waiting for the task to complete.

    Retorna: A `ValueTask` representing the asynchronous broadcast operation.

  • methodReceiveRemoteRevocationAsync
    public ValueTask ReceiveRemoteRevocationAsync(KeyIdentifier keyId, KeyVersion version, KeyPurpose purpose, CancellationToken cancellationToken = default)

    Ingests a remote key revocation event received from an external message bus or cluster subscriber. Evicts the specified key from local in-process key rings without republishing to the distributed bus.

    keyId: KeyIdentifier
    The identifier of the revoked key.
    version: KeyVersion
    The version of the revoked key.
    purpose: KeyPurpose
    The cryptographic purpose of the revoked key.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: A `ValueTask` representing the asynchronous operation.

  • methodSubscribe
    public IDisposable Subscribe(Action<KeyIdentifier, KeyVersion, KeyPurpose> handler)

    Registers a revocation listener callback invoked when a key revocation signal is received.

    handler: Action<KeyIdentifier, KeyVersion, KeyPurpose>
    The delegate invoked upon key revocation.

    Retorna: An `IDisposable` token that unregisters the callback upon disposal.

class

InMemoryKeyStore

Ensamblado: EricksonLopez.Security
public sealed class InMemoryKeyStore : IKeyStore
Implementa: IKeyStore

Provides a thread-safe in-memory key store implementation of `IKeyStore` suitable for testing, development, and containerized microservice deployments.

Miembros (6)

  • constructorInMemoryKeyStore
    public InMemoryKeyStore()

    Initializes a new instance of the `InMemoryKeyStore` class. Throws if the environment is set to Production to prevent data loss.

    Exceptions: NotSupportedException: The execution environment is set to Production

  • methodGetKeyAsync
    public ValueTask<Result<CryptographicKey>> GetKeyAsync(KeyIdentifier keyId, KeyVersion version, CancellationToken cancellationToken = default)

    Retrieves a cryptographic key by identifier and version.

    keyId: KeyIdentifier
    The key identifier.
    version: KeyVersion
    The key version.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the `CryptographicKey`.

  • methodListMetadataAsync
    public ValueTask<Result<IReadOnlyList<KeyMetadata>>> ListMetadataAsync(KeyPurpose? purpose = null, CancellationToken cancellationToken = default)

    Retrieves all key metadata stored in the repository.

    purpose: KeyPurpose?
    Optional purpose filter.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a result with a list of key metadata records.

  • methodSaveKeyAsync
    public ValueTask<Result> SaveKeyAsync(CryptographicKey key, CancellationToken cancellationToken = default)

    Persists a new cryptographic key into the key store.

    key: CryptographicKey
    The cryptographic key to save.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating success or failure.

  • methodUpdateStatusAsync
    public ValueTask<Result> UpdateStatusAsync(KeyIdentifier keyId, KeyVersion version, KeyStatus newStatus, CancellationToken cancellationToken = default)

    Updates the lifecycle status of a specific key.

    keyId: KeyIdentifier
    The key identifier.
    version: KeyVersion
    The key version.
    newStatus: KeyStatus
    The new lifecycle status.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating the outcome.

  • fieldMaxKeys
    public const int MaxKeys

    Maximum number of keys that can be stored in a single `InMemoryKeyStore` instance. Prevents unbounded memory growth if used as a long-lived store. See DOS-002, CON-003.

class

InProcessKeyRevocationNotifier

Ensamblado: EricksonLopez.Security
public sealed class InProcessKeyRevocationNotifier : IKeyRevocationNotifier
Implementa: IKeyRevocationNotifier

Provides a high-performance, in-process, thread-safe implementation of `IKeyRevocationNotifier`. Dispatches revocation events synchronously or asynchronously to registered in-process key rings.

Miembros (3)

  • constructorInProcessKeyRevocationNotifier
    public InProcessKeyRevocationNotifier()

    Initializes a new instance of the `InProcessKeyRevocationNotifier` class.

  • methodNotifyRevokedAsync
    public ValueTask NotifyRevokedAsync(KeyIdentifier keyId, KeyVersion version, KeyPurpose purpose, CancellationToken cancellationToken = default)

    Broadcasts a key revocation notification to all registered listeners.

    keyId: KeyIdentifier
    The identifier of the revoked key.
    version: KeyVersion
    The version of the revoked key.
    purpose: KeyPurpose
    The purpose of the revoked key.
    cancellationToken: CancellationToken
    A token to observe while waiting for the task to complete.

    Retorna: A `ValueTask` representing the asynchronous broadcast operation.

  • methodSubscribe
    public IDisposable Subscribe(Action<KeyIdentifier, KeyVersion, KeyPurpose> handler)

    Registers a revocation listener callback invoked when a key revocation signal is received.

    handler: Action<KeyIdentifier, KeyVersion, KeyPurpose>
    The delegate invoked upon key revocation.

    Retorna: An `IDisposable` token that unregisters the callback upon disposal.

class

KeyLifecycleManager

Ensamblado: EricksonLopez.Security
public sealed class KeyLifecycleManager : IKeyLifecycleManager, IDisposable
Implementa: IDisposable, IKeyLifecycleManager

Orchestrates cryptographic key generation, rotation, retirement, and revocation workflows.

Miembros (6)

  • constructorKeyLifecycleManager
    public KeyLifecycleManager(IKeyStore keyStore, Action<ISecurityEvent>? eventPublisher = null, bool failOnAuditFailure = false)

    Initializes a new instance of the `KeyLifecycleManager` class.

    keyStore: IKeyStore
    The key storage repository.
    eventPublisher: Action<ISecurityEvent>?
    Optional security event dispatcher delegate.
    failOnAuditFailure: bool
    Indicates whether event publisher exceptions should fail the operation (`true`, fail-stop for regulated environments) or be handled in degraded mode with diagnostic activity logging (`false`, default).

    Exceptions: ArgumentNullException: `keyStore` is `null`

  • constructorKeyLifecycleManager
    public KeyLifecycleManager(IKeyStore keyStore, Action<ISecurityEvent>? eventPublisher, bool failOnAuditFailure, IKeyRevocationNotifier? revocationNotifier)

    Initializes a new instance of the `KeyLifecycleManager` class with a revocation notifier.

    keyStore: IKeyStore
    The key storage repository.
    eventPublisher: Action<ISecurityEvent>?
    Optional security event dispatcher delegate.
    failOnAuditFailure: bool
    Indicates whether event publisher exceptions should fail the operation (`true`, fail-stop for regulated environments) or be handled in degraded mode with diagnostic activity logging (`false`, default).
    revocationNotifier: IKeyRevocationNotifier?
    Optional key revocation notifier for real-time cache invalidation.

    Exceptions: ArgumentNullException: `keyStore` is `null`

  • methodDispose
    public void Dispose()

    Inherits documentation from base type or interface.

  • methodGenerateAndActivateKeyAsync
    public async ValueTask<Result<CryptographicKey>> GenerateAndActivateKeyAsync(KeyPurpose purpose, string algorithmId = "", TimeSpan? validityPeriod = null, CancellationToken cancellationToken = default)

    Generates and activates a new cryptographic key for the specified purpose and algorithm.

    purpose: KeyPurpose
    The key purpose.
    algorithmId: string
    The algorithm identifier (e.g. "AES-256-GCM").
    validityPeriod: TimeSpan?
    Optional key expiration validity duration.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the generated and activated `CryptographicKey`.

  • methodRevokeKeyAsync
    public async ValueTask<Result> RevokeKeyAsync(KeyIdentifier keyId, KeyVersion version, string reason, CancellationToken cancellationToken = default)

    Revokes a specific key immediately, disabling it from all future encryption, signing, and decryption operations.

    keyId: KeyIdentifier
    The key identifier.
    version: KeyVersion
    The key version.
    reason: string
    The revocation reason.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating success or failure.

  • methodRotateKeyAsync
    public async ValueTask<Result<CryptographicKey>> RotateKeyAsync(KeyPurpose purpose, TimeSpan? validityPeriod = null, CancellationToken cancellationToken = default)

    Rotates the active key for a given purpose: marks the current active key as `KeyStatus.Retired` and generates a new active key with incremented version.

    purpose: KeyPurpose
    The key purpose to rotate.
    validityPeriod: TimeSpan?
    Optional validity period for the new key.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the newly active `CryptographicKey`.

class

KeyRing

Ensamblado: EricksonLopez.Security
public sealed class KeyRing : IKeyRing, IEncryptionKeyProvider, IDisposable
Implementa: IDisposable, IEncryptionKeyProvider, IKeyRing

Provides a thread-safe implementation of `IKeyRing` and `IEncryptionKeyProvider`. Resolves active and historical cryptographic keys from an underlying `IKeyStore`.

Miembros (15)

  • constructorKeyRing
    public KeyRing(IKeyStore keyStore)

    Initializes a new instance of the `KeyRing` class.

    keyStore: IKeyStore
    The underlying persistent or in-memory key store.

    Exceptions: ArgumentNullException: `keyStore` is `null`

  • constructorKeyRing
    public KeyRing(IKeyStore keyStore, KeyRingOptions? options)

    Initializes a new instance of the `KeyRing` class with configuration options.

    keyStore: IKeyStore
    The underlying persistent or in-memory key store.
    options: KeyRingOptions?
    Optional configuration options specifying caching behaviors.

    Exceptions: ArgumentNullException: `keyStore` is `null`

  • constructorKeyRing
    public KeyRing(IKeyStore keyStore, KeyRingOptions? options, IKeyRevocationNotifier? revocationNotifier)

    Initializes a new instance of the `KeyRing` class with configuration options and revocation notifier.

    keyStore: IKeyStore
    The underlying persistent or in-memory key store.
    options: KeyRingOptions?
    Optional configuration options specifying caching behaviors.
    revocationNotifier: IKeyRevocationNotifier?
    Optional key revocation notifier for real-time cache invalidation.

    Exceptions: ArgumentNullException: `keyStore` is `null`

  • methodDispose
    public void Dispose()

    Inherits documentation from base type or interface.

  • methodGetActiveEncryptionKeyAsync
    public ValueTask<Result<CryptographicKey>> GetActiveEncryptionKeyAsync(KeyPurpose purpose = KeyPurpose.Encryption, CancellationToken cancellationToken = default)

    Gets the current active key for encryption operations.

    purpose: KeyPurpose
    The key purpose (defaults to Encryption).
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the active `CryptographicKey`.

  • methodGetActiveKey
    public Result<CryptographicKey> GetActiveKey(KeyPurpose purpose)

    Synchronously retrieves the current active key for a given purpose.

    purpose: KeyPurpose
    The key purpose.

    Retorna: A `Result<T>` containing the active `CryptographicKey`.

    Performance Note (REM-03): Resolves active keys from the local in-memory cache on cache hits with zero async overhead. In asynchronous workflows, always prefer `GetActiveKeyAsync(KeyPurpose, CancellationToken)` for non-cached resolution.

  • methodGetActiveKeyAsync
    public async ValueTask<Result<CryptographicKey>> GetActiveKeyAsync(KeyPurpose purpose, CancellationToken cancellationToken = default)

    Asynchronously retrieves the current active key for a given purpose.

    purpose: KeyPurpose
    The key purpose.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the active `CryptographicKey`.

  • methodGetDecryptionKeyAsync
    public ValueTask<Result<CryptographicKey>> GetDecryptionKeyAsync(KeyIdentifier keyId, KeyVersion version, CancellationToken cancellationToken = default)

    Gets a specific versioned key for decryption operations.

    keyId: KeyIdentifier
    The key identifier.
    version: KeyVersion
    The key version.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the requested `CryptographicKey`.

  • methodGetKey
    public Result<CryptographicKey> GetKey(KeyIdentifier keyId, KeyVersion version)

    Synchronously retrieves a specific versioned key for decryption or verification.

    keyId: KeyIdentifier
    The key identifier.
    version: KeyVersion
    The key version.

    Retorna: A `Result<T>` containing the requested `CryptographicKey`.

    Performance Note (REM-03): Resolves versioned keys from the local in-memory cache on cache hits with zero async overhead. In asynchronous workflows, always prefer `GetKeyAsync(KeyIdentifier, KeyVersion, CancellationToken)` for non-cached resolution.

  • methodGetKeyAsync
    public async ValueTask<Result<CryptographicKey>> GetKeyAsync(KeyIdentifier keyId, KeyVersion version, CancellationToken cancellationToken = default)

    Asynchronously retrieves a specific versioned key for decryption or verification.

    keyId: KeyIdentifier
    The key identifier.
    version: KeyVersion
    The key version.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the requested `CryptographicKey`.

  • methodInvalidateActiveKey
    public void InvalidateActiveKey(KeyPurpose purpose)

    Immediately evicts and scrubs the active key for a given purpose from the local cache.

    purpose: KeyPurpose
    The key purpose whose active cached key should be evicted.
  • methodInvalidateAll
    public void InvalidateAll()

    Immediately evicts and scrubs all cached keys and metadata from the local cache.

  • methodInvalidateKey
    public void InvalidateKey(KeyIdentifier keyId, KeyVersion version)

    Immediately evicts and scrubs a specific versioned key from the local cache.

    keyId: KeyIdentifier
    The identifier of the key to evict.
    version: KeyVersion
    The version of the key to evict.
  • methodListMetadataAsync
    public ValueTask<Result<IReadOnlyList<KeyMetadata>>> ListMetadataAsync(KeyPurpose? purpose = null, CancellationToken cancellationToken = default)

    Asynchronously lists all known key metadata descriptors currently loaded in the key ring.

    purpose: KeyPurpose?
    Optional purpose filter.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a result with a list of key metadata records.

  • propertyCacheTtl
    public static TimeSpan CacheTtl { get; set; }

    Gets or sets the global default time-to-live for in-memory cached cryptographic keys. Defaults to 30 seconds to minimize plaintext exposure in memory dumps. Set to `TimeSpan.Zero` to disable caching. Prefer configuring via `KeyRingOptions` in dependency injection containers.

class

KeyRingOptions

Ensamblado: EricksonLopez.Security
public sealed class KeyRingOptions

Specifies configuration options for `KeyRing` instance-level caching and lifecycle behaviors.

Miembros (2)

  • constructorKeyRingOptions
    public KeyRingOptions()

    Initializes a new instance of the `KeyRingOptions` class.

  • propertyCacheTtl
    public TimeSpan CacheTtl { get; set; }

    Gets or sets the time-to-live for in-memory cached cryptographic keys. Defaults to 30 seconds to minimize plaintext exposure in memory dumps. Set to `TimeSpan.Zero` to disable caching.

record

KmsWrappedRsaKeyMaterial

Ensamblado: EricksonLopez.Security
public sealed record KmsWrappedRsaKeyMaterial(string KeyId, byte[] WrappedPrivateKeyPkcs8, string PublicKeyPem, RsaPublicKeyDescriptor PublicKeyDescriptor, int KeySizeInBits, DateTimeOffset CreatedAtUtc)

Represents newly generated or wrapped RSA signing key material whose PKCS#8 private key is KMS-envelope encrypted and cryptographically bound to `KeyId` via Authenticated Associated Data (AAD).

Miembros (7)

  • constructorKmsWrappedRsaKeyMaterial
    public KmsWrappedRsaKeyMaterial(string KeyId, byte[] WrappedPrivateKeyPkcs8, string PublicKeyPem, RsaPublicKeyDescriptor PublicKeyDescriptor, int KeySizeInBits, DateTimeOffset CreatedAtUtc)

    Initializes a new instance of KmsWrappedRsaKeyMaterial.

    KeyId: string
    The unique key identifier (`kid`) bound to the wrapped private key.
    WrappedPrivateKeyPkcs8: byte[]
    The KMS-wrapped PKCS#8 private key ciphertext bytes.
    PublicKeyPem: string
    The SubjectPublicKeyInfo (`PUBLIC KEY`) PEM representation of the public key.
    PublicKeyDescriptor: RsaPublicKeyDescriptor
    The JWKS-ready public key descriptor containing modulus and exponent.
    KeySizeInBits: int
    The RSA modulus size in bits (for example, 3072 or 4096).
    CreatedAtUtc: DateTimeOffset
    The UTC timestamp when the key material was generated or wrapped.
  • propertyCreatedAtUtc
    public DateTimeOffset CreatedAtUtc { get; init; }

    The UTC timestamp when the key material was generated or wrapped.

  • propertyKeyId
    public string KeyId { get; init; }

    The unique key identifier (`kid`) bound to the wrapped private key.

  • propertyKeySizeInBits
    public int KeySizeInBits { get; init; }

    The RSA modulus size in bits (for example, 3072 or 4096).

  • propertyPublicKeyDescriptor
    public RsaPublicKeyDescriptor PublicKeyDescriptor { get; init; }

    The JWKS-ready public key descriptor containing modulus and exponent.

  • propertyPublicKeyPem
    public string PublicKeyPem { get; init; }

    The SubjectPublicKeyInfo (`PUBLIC KEY`) PEM representation of the public key.

  • propertyWrappedPrivateKeyPkcs8
    public byte[] WrappedPrivateKeyPkcs8 { get; init; }

    The KMS-wrapped PKCS#8 private key ciphertext bytes.

class

LocalAesGcmKmsKeyWrappingProvider

Ensamblado: EricksonLopez.Security
public sealed class LocalAesGcmKmsKeyWrappingProvider : IKmsKeyWrappingProvider, IDisposable
Implementa: IDisposable, IKmsKeyWrappingProvider

Provides a local, self-hosted AEAD Key Encryption Key (KEK) implementation of `IKmsKeyWrappingProvider` using HKDF-SHA256 per-operation subkey isolation and AES-256-GCM authenticated encryption.

Notas:

Suitable for development, deterministic automated testing, and self-hosted deployments where an external Cloud KMS is not provisioned.

Miembros (7)

  • constructorLocalAesGcmKmsKeyWrappingProvider
    public LocalAesGcmKmsKeyWrappingProvider(ReadOnlySpan<byte> keyEncryptionKey, bool requireAssociatedData = false)

    Initializes a new instance of the `LocalAesGcmKmsKeyWrappingProvider` class with a 256-bit KEK.

    keyEncryptionKey: ReadOnlySpan<byte>
    The 32-byte (256-bit) Key Encryption Key material.
    requireAssociatedData: bool
    When `true`, empty AAD is rejected fail-closed.

    Exceptions: ArgumentException: `keyEncryptionKey` is not exactly 32 bytes.

  • methodCreateEphemeral
    public static LocalAesGcmKmsKeyWrappingProvider CreateEphemeral(bool requireAssociatedData = false)

    Creates an ephemeral in-memory `LocalAesGcmKmsKeyWrappingProvider` backed by 256 bits of CSPRNG entropy.

    requireAssociatedData: bool
    When `true`, empty AAD is rejected fail-closed.

    Retorna: A newly initialized `LocalAesGcmKmsKeyWrappingProvider`.

  • methodDispose
    public void Dispose()

    Scrubs the Key Encryption Key from memory.

  • methodUnwrapKeyAsync
    public ValueTask<Result<ISecretBuffer>> UnwrapKeyAsync(ReadOnlyMemory<byte> wrappedKey, ReadOnlyMemory<byte> associatedData = default, CancellationToken cancellationToken = default)

    Decrypts (unwraps) previously wrapped key material into a deterministic memory-scrubbing `ISecretBuffer`.

    wrappedKey: ReadOnlyMemory<byte>
    The wrapped key ciphertext bytes produced by `WrapKeyAsync`.
    associatedData: ReadOnlyMemory<byte>
    Optional authenticated associated data that must match the AAD used when wrapping.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A `Result<T>` containing a disposable `ISecretBuffer` whose memory is zeroed on disposal, or a typed security error.

  • methodWrapKeyAsync
    public ValueTask<Result<byte[]>> WrapKeyAsync(ReadOnlyMemory<byte> plaintextKey, ReadOnlyMemory<byte> associatedData = default, CancellationToken cancellationToken = default)

    Encrypts (wraps) raw Data Encryption Key (DEK) or PKCS#8 asymmetric private key material under the configured KEK.

    plaintextKey: ReadOnlyMemory<byte>
    The raw key material to wrap. Must not be empty.
    associatedData: ReadOnlyMemory<byte>
    Optional authenticated associated data (for example, key identifier or tenant binding) bound to the wrapped key.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A `Result<T>` containing the opaque wrapped key ciphertext bytes on success, or a typed security error.

  • propertyIsDisposed
    public bool IsDisposed { get; }

    Gets a value indicating whether this instance has been disposed and its KEK wiped from memory.

  • propertyRequireAssociatedData
    public bool RequireAssociatedData { get; }

    Gets a value indicating whether non-empty associated data is required on wrap and unwrap operations.

class

RsaKeyEnvelopeProtector

Ensamblado: EricksonLopez.Security
public sealed class RsaKeyEnvelopeProtector

Generates, wraps, and unwraps PKCS#8 RSA signing key pairs via `IKmsKeyWrappingProvider` with mandatory `kid` Authenticated Associated Data (AAD) binding, deterministic buffer zeroing, and leak-free native `RSA` handle lifecycle management.

Miembros (11)

  • constructorRsaKeyEnvelopeProtector
    public RsaKeyEnvelopeProtector(IKmsKeyWrappingProvider wrappingProvider, TimeProvider? timeProvider = null, string aadDomainPrefix = "")

    Initializes a new instance of the `RsaKeyEnvelopeProtector` class.

    wrappingProvider: IKmsKeyWrappingProvider
    The KMS or AEAD KEK key-wrapping provider.
    timeProvider: TimeProvider?
    Optional time provider (defaults to `TimeProvider.System`).
    aadDomainPrefix: string
    Domain-separation prefix bound into the `kid` AAD context.

    Exceptions: ArgumentNullException: `wrappingProvider` is `null`.; ArgumentException: `aadDomainPrefix` is null or whitespace.

  • methodBuildKeyBindingAssociatedData
    public byte[] BuildKeyBindingAssociatedData(string keyId, ReadOnlySpan<byte> additionalAssociatedData = default)

    Builds the canonical UTF-8 AAD byte representation binding a wrapped RSA key to its `keyId` and optional `additionalAssociatedData`.

    keyId: string
    The non-empty key identifier (`kid`).
    additionalAssociatedData: ReadOnlySpan<byte>
    Optional additional context bytes appended after the canonical `kid` binding.

    Retorna: The canonical AAD byte array.

    Exceptions: ArgumentException: `keyId` is null or whitespace.

  • methodCreateKeyRingFromWrappedAsync
    public async ValueTask<Result<IRsaKeyRing>> CreateKeyRingFromWrappedAsync(string keyId, ReadOnlyMemory<byte> wrappedPrivateKeyPkcs8, ReadOnlyMemory<byte> additionalAssociatedData = default, CancellationToken cancellationToken = default)

    Unwraps KMS-protected PKCS#8 RSA private key material and initializes a new in-memory `IRsaKeyRing`, scrubbing all intermediate private buffers before returning.

    keyId: string
    The non-empty `kid` bound in AAD.
    wrappedPrivateKeyPkcs8: ReadOnlyMemory<byte>
    The KMS-wrapped PKCS#8 private key ciphertext.
    additionalAssociatedData: ReadOnlyMemory<byte>
    Optional additional context bound into the KMS AAD.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A `Result<T>` containing the initialized `IRsaKeyRing`.

  • methodGenerateAndWrapKeyAsync
    public async ValueTask<Result<KmsWrappedRsaKeyMaterial>> GenerateAndWrapKeyAsync(string keyId, int keySizeInBits = DefaultRsaKeySizeBits, ReadOnlyMemory<byte> additionalAssociatedData = default, CancellationToken cancellationToken = default)

    Generates a new RSA key pair (`keySizeInBits` >= 2048, default 3072), exports its PKCS#8 private key into a zeroizable buffer, wraps it via `IKmsKeyWrappingProvider` with `keyId` AAD binding, and disposes the native `RSA` handle deterministically.

    keyId: string
    The non-empty `kid` for the new RSA key pair.
    keySizeInBits: int
    The RSA modulus size in bits (minimum 2048, default 3072, maximum 8192).
    additionalAssociatedData: ReadOnlyMemory<byte>
    Optional additional context bound into the KMS AAD.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A `Result<T>` containing the `KmsWrappedRsaKeyMaterial` on success.

  • methodScrubPrivateParameters
    public static void ScrubPrivateParameters(ref RSAParameters parameters)

    Zeroes all private components (`D`, `P`, `Q`, `DP`, `DQ`, `InverseQ`) of an `RSAParameters` structure.

    parameters: ref RSAParameters
    The RSA parameters structure to scrub.
  • methodUnwrapAndActivateInKeyRingAsync
    public async ValueTask<Result<RsaPublicKeyDescriptor>> UnwrapAndActivateInKeyRingAsync(IRsaKeyRing keyRing, string keyId, ReadOnlyMemory<byte> wrappedPrivateKeyPkcs8, TimeSpan? previousKeyOverlapWindow = null, ReadOnlyMemory<byte> additionalAssociatedData = default, CancellationToken cancellationToken = default)

    Unwraps KMS-protected PKCS#8 RSA private key material, activates it inside `keyRing`, and deterministically zeroes all intermediate private parameter buffers.

    keyRing: IRsaKeyRing
    The target `IRsaKeyRing` to rotate.
    keyId: string
    The non-empty `kid` bound in AAD.
    wrappedPrivateKeyPkcs8: ReadOnlyMemory<byte>
    The KMS-wrapped PKCS#8 private key ciphertext.
    previousKeyOverlapWindow: TimeSpan?
    Optional overlap window for the previously active verification key.
    additionalAssociatedData: ReadOnlyMemory<byte>
    Optional additional context bound into the KMS AAD.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A `Result<T>` containing the activated `RsaPublicKeyDescriptor`.

  • methodUnwrapToRsaParametersAsync
    public async ValueTask<Result<RSAParameters>> UnwrapToRsaParametersAsync(string keyId, ReadOnlyMemory<byte> wrappedPrivateKeyPkcs8, ReadOnlyMemory<byte> additionalAssociatedData = default, CancellationToken cancellationToken = default)

    Unwraps KMS-protected PKCS#8 RSA private key bytes verifying `keyId` AAD binding, imports them into an ephemeral disposed `RSA` instance, and exports `RSAParameters`.

    keyId: string
    The expected `kid` bound in AAD.
    wrappedPrivateKeyPkcs8: ReadOnlyMemory<byte>
    The KMS-wrapped PKCS#8 private key ciphertext.
    additionalAssociatedData: ReadOnlyMemory<byte>
    Optional additional context bound into the KMS AAD.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A `Result<T>` containing the unwrapped `RSAParameters` on success.

    Callers MUST scrub private arrays on the returned `RSAParameters` via `ScrubPrivateParameters` once imported, or prefer `UnwrapAndActivateInKeyRingAsync` / `CreateKeyRingFromWrappedAsync`.

  • methodWrapExistingKeyAsync
    public async ValueTask<Result<KmsWrappedRsaKeyMaterial>> WrapExistingKeyAsync(string keyId, RSA rsa, ReadOnlyMemory<byte> additionalAssociatedData = default, CancellationToken cancellationToken = default)

    Exports the PKCS#8 private key from an existing `rsa` instance into a zeroizable buffer and wraps it via `IKmsKeyWrappingProvider` bound to `keyId` without disposing `rsa`.

    keyId: string
    The non-empty `kid` to bind into AAD.
    rsa: RSA
    The existing RSA instance containing private key parameters.
    additionalAssociatedData: ReadOnlyMemory<byte>
    Optional additional context bound into the KMS AAD.
    cancellationToken: CancellationToken
    A token to cancel the asynchronous operation.

    Retorna: A `Result<T>` containing the `KmsWrappedRsaKeyMaterial` on success.

  • fieldDefaultRsaKeySizeBits
    public const int DefaultRsaKeySizeBits

    Gets the default recommended RSA modulus size in bits (3072 bits per NIST SP 800-57).

  • fieldMaximumRsaKeySizeBits
    public const int MaximumRsaKeySizeBits

    Gets the maximum allowed RSA modulus size in bits (8192 bits).

  • fieldMinimumRsaKeySizeBits
    public const int MinimumRsaKeySizeBits

    Gets the minimum allowed RSA modulus size in bits (2048 bits).

class

RsaKeyRing

Ensamblado: EricksonLopez.Security
public sealed class RsaKeyRing : IRsaKeyRing
Implementa: IRsaKeyRing

Provides a thread-safe, pure in-memory multi-`kid` RSA key ring for asymmetric signing (RS256/PS256), zero-downtime key rotation with bounded overlap verification windows, JWKS Base64Url public parameter export, and deterministic `ZeroMemory` wiping of superseded private parameters without touching disk PEM files.

Miembros (15)

  • constructorRsaKeyRing
    public RsaKeyRing(string activeKeyId, RSAParameters activeParameters, TimeProvider? timeProvider = null)

    Initializes a new instance of the `RsaKeyRing` class from in-memory `RSAParameters`.

    activeKeyId: string
    The non-empty `kid` identifying the active signing key.
    activeParameters: RSAParameters
    The private and public RSA parameters (minimum 2048-bit modulus).
    timeProvider: TimeProvider?
    Optional time provider (defaults to `TimeProvider.System`).

    Exceptions: ArgumentException: Key identifier is empty, private parameters are missing, or modulus is smaller than 2048 bits.

  • constructorRsaKeyRing
    public RsaKeyRing(string activeKeyId, ReadOnlySpan<char> privateKeyPem, TimeProvider? timeProvider = null)

    Initializes a new instance of the `RsaKeyRing` class from an in-memory PEM-encoded RSA private key.

    activeKeyId: string
    The non-empty `kid` identifying the active signing key.
    privateKeyPem: ReadOnlySpan<char>
    The in-memory PEM-encoded RSA private key (`RSA PRIVATE KEY` or `PRIVATE KEY`).
    timeProvider: TimeProvider?
    Optional time provider (defaults to `TimeProvider.System`).

    Exceptions: ArgumentException: `activeKeyId` or `privateKeyPem` is empty, malformed, or smaller than 2048 bits.

  • methodCreateEphemeral
    public static RsaKeyRing CreateEphemeral(string activeKeyId = "", int keySizeInBits = MinimumRsaKeySizeBits, TimeProvider? timeProvider = null)

    Generates a new pure in-memory CSPRNG RSA key ring without reading or writing PEM files on disk.

    activeKeyId: string
    The non-empty `kid` for the generated key.
    keySizeInBits: int
    The RSA modulus size in bits (minimum 2048, default 2048).
    timeProvider: TimeProvider?
    Optional time provider (defaults to `TimeProvider.System`).

    Retorna: A newly initialized `RsaKeyRing`.

  • methodDispose
    public void Dispose()

    Inherits documentation from base type or interface.

  • methodExportActivePublicKey
    public RsaPublicKeyDescriptor ExportActivePublicKey()

    Exports the public key descriptor for the currently active signing key.

    Retorna: The `RsaPublicKeyDescriptor` of the active key.

  • methodExportActiveSigningParameters
    public (string KeyId, RSAParameters Parameters) ExportActiveSigningParameters()

    Exports a defensive copy of the currently active signing key's private and public `RSAParameters`. Callers must scrub private parameter arrays after importing them into ephemeral `RSA` or signing wrappers.

    Retorna: A tuple containing the active `kid` and its cloned `RSAParameters`.

  • methodGenerateAndActivateKey
    public RsaPublicKeyDescriptor GenerateAndActivateKey(string newKeyId, int keySizeInBits = MinimumRsaKeySizeBits, TimeSpan? previousKeyOverlapWindow = null)

    Generates a new in-memory RSA key pair of at least 2048 bits, promotes it to active signing key, retains the previous public key in the validation ring for `previousKeyOverlapWindow`, and zeroes the superseded private key parameters in memory.

    newKeyId: string
    The non-empty `kid` for the newly generated key.
    keySizeInBits: int
    The RSA modulus size in bits (minimum 2048, default 2048).
    previousKeyOverlapWindow: TimeSpan?
    Optional overlap validity window for the previously active public key (defaults to 24 hours).

    Retorna: The `RsaPublicKeyDescriptor` of the newly activated key.

  • methodGetValidationKeys
    public IReadOnlyList<RsaPublicKeyDescriptor> GetValidationKeys()

    Returns all currently valid (non-expired) RSA public verification keys in the key ring.

    Retorna: An immutable snapshot of active and overlap `RsaPublicKeyDescriptor` entries.

  • methodRegisterPublicValidationKeyPem
    public RsaPublicKeyDescriptor RegisterPublicValidationKeyPem(string keyId, ReadOnlySpan<char> publicKeyPem, DateTimeOffset? expiresAtUtc = null)

    Registers an additional public-only RSA key in the validation ring (for example, a historical key during startup overlap).

    keyId: string
    The non-empty `kid` of the public validation key.
    publicKeyPem: ReadOnlySpan<char>
    The PEM-encoded public key (`PUBLIC KEY` or `RSA PUBLIC KEY`).
    expiresAtUtc: DateTimeOffset?
    Optional UTC expiration timestamp for the overlap key.

    Retorna: The registered `RsaPublicKeyDescriptor`.

  • methodRegisterRotatedKey
    public RsaPublicKeyDescriptor RegisterRotatedKey(string newKeyId, RSAParameters fullParameters, TimeSpan? previousKeyOverlapWindow = null)

    Promotes externally supplied private `RSAParameters` to the active signing key, retains the previous public key in the validation ring for `previousKeyOverlapWindow`, and zeroes the superseded private key parameters in memory.

    newKeyId: string
    The non-empty `kid` for the rotated key.
    fullParameters: RSAParameters
    The full private and public RSA parameters (minimum 2048-bit modulus).
    previousKeyOverlapWindow: TimeSpan?
    Optional overlap validity window for the previously active public key.

    Retorna: The `RsaPublicKeyDescriptor` of the newly activated key.

  • methodRemoveValidationKey
    public bool RemoveValidationKey(string keyId)

    Immediately removes a non-active validation key from the public verification ring (for example, upon emergency key revocation).

    keyId: string
    The `kid` to remove. Cannot be the currently active `ActiveKeyId`.

    Retorna: `true` if the validation key was found and removed; otherwise, `false`.

  • methodSignDataSha256
    public byte[] SignDataSha256(ReadOnlySpan<byte> data, RSASignaturePadding? padding = null)

    Computes an RSA-SHA256 digital signature over `data` using the active private key.

    data: ReadOnlySpan<byte>
    The message bytes to sign.
    padding: RSASignaturePadding?
    Optional RSA signature padding (defaults to `RSASignaturePadding.Pkcs1` for RS256).

    Retorna: The raw RSA signature bytes.

  • methodVerifyDataSha256
    public bool VerifyDataSha256(ReadOnlySpan<byte> data, ReadOnlySpan<byte> signature, string? keyId = null, RSASignaturePadding? padding = null)

    Verifies an RSA-SHA256 signature against a specific `keyId` (when provided) or across all non-expired validation keys in the ring.

    data: ReadOnlySpan<byte>
    The signed message bytes.
    signature: ReadOnlySpan<byte>
    The RSA signature bytes to verify.
    keyId: string?
    Optional `kid` header hint restricting verification to that specific key.
    padding: RSASignaturePadding?
    Optional RSA signature padding (defaults to `RSASignaturePadding.Pkcs1` for RS256).

    Retorna: `true` if the signature is cryptographically valid for a non-expired validation key; otherwise, `false`.

  • propertyActiveKeyId
    public string ActiveKeyId { get; }

    Gets the identifier (`kid`) of the currently active signing key.

  • propertyIsDisposed
    public bool IsDisposed { get; }

    Gets a value indicating whether this instance has been disposed.

class

RsaKeyRingProvider

Ensamblado: EricksonLopez.Security
public sealed class RsaKeyRingProvider : IDisposable
Implementa: IDisposable

Thread-safe asymmetric RSA signing key ring provider managing cached `RSA` signing handles per `kid`, zero-downtime key rotation, public JWKS descriptor export, and deterministic `ZeroMemory` disposal.

Miembros (9)

  • constructorRsaKeyRingProvider
    public RsaKeyRingProvider(RsaKeyRing keyRing)

    Initializes a new instance of the `RsaKeyRingProvider` class wrapping an existing `RsaKeyRing`.

    keyRing: RsaKeyRing
    The underlying multi-`kid` RSA key ring.
  • constructorRsaKeyRingProvider
    public RsaKeyRingProvider(string activeKeyId, ReadOnlySpan<char> privateKeyPem, TimeProvider? timeProvider = null)

    Initializes a new instance of the `RsaKeyRingProvider` class from PEM-encoded RSA private key material.

    activeKeyId: string
    The active signing key identifier (`kid`).
    privateKeyPem: ReadOnlySpan<char>
    The PEM-encoded RSA private key (minimum 2048 bits).
    timeProvider: TimeProvider?
    Optional time provider.
  • methodDispose
    public void Dispose()

    Inherits documentation from base type or interface.

  • methodGetActiveSigningKey
    public (string KeyId, RSA Rsa) GetActiveSigningKey()

    Obtains the cached `RSA` signing instance and `kid` for the active key without allocating duplicate native handles per token.

    Retorna: A tuple of active `KeyId` and reusable `RSA` handle owned by this provider.

  • methodGetValidationKeys
    public IReadOnlyList<RsaPublicKeyDescriptor> GetValidationKeys()

    Returns all currently valid public RSA verification key descriptors (active + non-expired overlap keys).

    Retorna: A read-only list of `RsaPublicKeyDescriptor` entries.

  • methodRotateSigningKey
    public RsaPublicKeyDescriptor RotateSigningKey(string newKeyId, RSAParameters fullParameters, TimeSpan? previousKeyOverlapWindow = null)

    Rotates the active signing key to `newKeyId` and retains the previous public key for `previousKeyOverlapWindow`.

    newKeyId: string
    The new active `kid`.
    fullParameters: RSAParameters
    The full 2048-bit+ RSA parameters.
    previousKeyOverlapWindow: TimeSpan?
    Optional overlap verification window (defaults to 24 hours).

    Retorna: The public key descriptor of the newly activated key.

  • methodSignDataSha256
    public byte[] SignDataSha256(ReadOnlySpan<byte> data)

    Signs `data` using RSASSA-PKCS1-v1_5 SHA-256 with the active signing key.

    data: ReadOnlySpan<byte>
    The payload bytes to sign.

    Retorna: The RSA-SHA256 signature bytes.

  • propertyActiveKeyId
    public string ActiveKeyId { get; }

    Gets the active signing key identifier (`kid`).

  • propertyKeyRing
    public IRsaKeyRing KeyRing { get; }

    Gets the underlying `IRsaKeyRing`.

EricksonLopez.Security.Media#

3
class

BinaryImageInspector

Ensamblado: EricksonLopez.Security
public static class BinaryImageInspector

Inspects untrusted binary image uploads using pure `ReadOnlySpan<T>` magic-byte and container header parsing (PNG `IHDR`, JPEG `SOF0..SOF15`, and WebP `VP8 /VP8L/VP8X`) without invoking native image decoders. Rejects SVG/XML/script polyglots, PE/ZIP headers, and decompression bombs.

Miembros (1)

  • methodInspect
    public static Result<InspectedImageMetadata> Inspect(ReadOnlySpan<byte> data, ImageSecurityPolicy? policy = null, string? originalFileName = null)

    Inspects `data` against `policy` and optional `originalFileName`.

    data: ReadOnlySpan<byte>
    The raw uploaded image bytes.
    policy: ImageSecurityPolicy?
    Optional security policy; defaults to `ImageSecurityPolicy.Default`.
    originalFileName: string?
    Optional original filename checked against forbidden executable/markup extensions.

    Retorna: Verified `InspectedImageMetadata` on success; otherwise, a validation error.

class

ImageSecurityPolicy

Ensamblado: EricksonLopez.Security
public sealed class ImageSecurityPolicy

Defines maximum byte size, pixel dimension bounds, and decompression-bomb ceilings for `BinaryImageInspector`.

Miembros (6)

  • propertyAllowWebP
    public bool AllowWebP { get; set; }

    Gets or sets a value indicating whether WebP images (`image/webp`) are accepted alongside PNG and JPEG. Defaults to `true`.

  • propertyDefault
    public static ImageSecurityPolicy Default { get; }

    Gets a shared default policy (2 MiB max size, 4096x4096 px max dimensions, 16,777,216 max total pixels).

  • propertyMaxBytes
    public int MaxBytes { get; set; }

    Gets or sets the maximum allowed payload size in bytes. Defaults to 2 MiB (2,097,152 bytes).

  • propertyMaxHeightPx
    public int MaxHeightPx { get; set; }

    Gets or sets the maximum allowed height in pixels. Defaults to 4096.

  • propertyMaxTotalPixels
    public long MaxTotalPixels { get; set; }

    Gets or sets the maximum total pixel area (`Width * Height`) to block decompression bombs. Defaults to 16,777,216 pixels.

  • propertyMaxWidthPx
    public int MaxWidthPx { get; set; }

    Gets or sets the maximum allowed width in pixels. Defaults to 4096.

record

InspectedImageMetadata

Ensamblado: EricksonLopez.Security
public sealed record InspectedImageMetadata(string MimeType, int WidthPx, int HeightPx, int ByteSize, string Sha256Hex)

Represents the verified MIME type, pixel dimensions, byte size, and SHA-256 digest of a binary-inspected raster image.

Miembros (6)

  • constructorInspectedImageMetadata
    public InspectedImageMetadata(string MimeType, int WidthPx, int HeightPx, int ByteSize, string Sha256Hex)

    Initializes a new instance of InspectedImageMetadata.

    MimeType: string
    The verified canonical MIME type (`image/png`, `image/jpeg`, or `image/webp`).
    WidthPx: int
    The verified pixel width extracted from binary container headers.
    HeightPx: int
    The verified pixel height extracted from binary container headers.
    ByteSize: int
    The exact byte length of the image payload.
    Sha256Hex: string
    The lowercase 64-character SHA-256 hex digest of the payload.
  • propertyByteSize
    public int ByteSize { get; init; }

    The exact byte length of the image payload.

  • propertyHeightPx
    public int HeightPx { get; init; }

    The verified pixel height extracted from binary container headers.

  • propertyMimeType
    public string MimeType { get; init; }

    The verified canonical MIME type (`image/png`, `image/jpeg`, or `image/webp`).

  • propertySha256Hex
    public string Sha256Hex { get; init; }

    The lowercase 64-character SHA-256 hex digest of the payload.

  • propertyWidthPx
    public int WidthPx { get; init; }

    The verified pixel width extracted from binary container headers.

EricksonLopez.Security.Mediator#

10
class

AllowAnonymousRequestAttribute

Ensamblado: EricksonLopez.Security.Mediator
public sealed class AllowAnonymousRequestAttribute : Attribute
Hereda de: Attribute

Marks a Mediator request as explicitly callable without authentication.

Miembros (0)

Este tipo declara 0 miembros públicos (por ejemplo, interfaz marcadora o enum/record vacío).

class

AllowAnyAuthenticatedUserAttribute

Ensamblado: EricksonLopez.Security.Mediator
public sealed class AllowAnyAuthenticatedUserAttribute : Attribute
Hereda de: Attribute

Marks a Mediator request as executable by any active authenticated human user without requiring a specific permission code.

Miembros (0)

Este tipo declara 0 miembros públicos (por ejemplo, interfaz marcadora o enum/record vacío).

interface

ISecurityFailureResultFactory<TResponse>

Ensamblado: EricksonLopez.Security.Mediator
public interface ISecurityFailureResultFactory<TResponse>

Constructs typed failure responses (`TResponse`) from a structured `Error` without runtime reflection.

Notas:

Type parameters: TResponse: The Mediator response type.

Miembros (1)

  • methodCreateFailure
    TResponse CreateFailure(Error failureError)

    Creates a failed `TResponse` wrapping `failureError`.

    failureError: Error
    The authorization error.

    Retorna: The failed `TResponse` instance.

interface

ITenantScopedRequest

Ensamblado: EricksonLopez.Security.Mediator
public interface ITenantScopedRequest

Marks a Mediator command or query that targets an explicit tenant identifier so `ZeroTrustAuthorizationBehavior<TRequest, TResponse>` prevents cross-tenant parameter tampering.

Miembros (1)

  • propertyTargetTenantId
    Guid TargetTenantId { get; }

    Gets the target tenant identifier declared on the request payload.

interface

IZeroTrustSecurityContext

Ensamblado: EricksonLopez.Security.Mediator
public interface IZeroTrustSecurityContext

Provides the ambient principal, security plane, assurance level, tenant/company scope, and effective permissions evaluated by `ZeroTrustAuthorizationBehavior<TRequest, TResponse>`.

Miembros (9)

  • propertyAssuranceLevel
    AuthenticationAssuranceLevel AssuranceLevel { get; }

    Gets the caller's `AuthenticationAssuranceLevel`.

  • propertyCompanyId
    Guid? CompanyId { get; }

    Gets the caller's active company identifier, if bound to a company.

  • propertyIsActive
    bool IsActive { get; }

    Gets a value indicating whether the authenticated principal and membership context are currently active.

  • propertyIsAuthenticated
    bool IsAuthenticated { get; }

    Gets a value indicating whether the current caller is authenticated.

  • propertyIsBackgroundExecution
    bool IsBackgroundExecution { get; }

    Gets a value indicating whether the current operation is running inside a trusted internal background job scope.

  • propertyPermissions
    IReadOnlySet<string> Permissions { get; }

    Gets the effective permission codes granted to the caller.

  • propertyPlane
    SecurityPlane Plane { get; }

    Gets the caller's `SecurityPlane`.

  • propertyPreAuthScope
    string? PreAuthScope { get; }

    Gets an optional restricted pre-authentication token scope (when non-null, operational requests are denied).

  • propertyTenantId
    Guid? TenantId { get; }

    Gets the caller's active tenant identifier, if bound to a tenant.

class

RequireAalAttribute

Ensamblado: EricksonLopez.Security.Mediator
public sealed class RequireAalAttribute : Attribute
Hereda de: Attribute

Declares the minimum NIST SP 800-63B `AuthenticationAssuranceLevel` required to execute a Mediator request.

Miembros (2)

  • constructorRequireAalAttribute
    public RequireAalAttribute(AuthenticationAssuranceLevel minimumAal)

    Initializes a new instance of the `RequireAalAttribute` class.

    minimumAal: AuthenticationAssuranceLevel
    The minimum required assurance level.
  • propertyMinimumAal
    public AuthenticationAssuranceLevel MinimumAal { get; }

    Gets the minimum required `AuthenticationAssuranceLevel`.

class

RequirePermissionAttribute

Ensamblado: EricksonLopez.Security.Mediator
public sealed class RequirePermissionAttribute : Attribute
Hereda de: Attribute

Declares one or more atomic RBAC permission codes required to execute a Mediator command or query.

Miembros (2)

  • constructorRequirePermissionAttribute
    public RequirePermissionAttribute(params string[] permissions)

    Initializes a new instance of the `RequirePermissionAttribute` class.

    permissions: params string[]
    One or more required atomic permission codes.
  • propertyPermissions
    public string[] Permissions { get; }

    Gets the required permission codes.

class

RequirePlaneAttribute

Ensamblado: EricksonLopez.Security.Mediator
public sealed class RequirePlaneAttribute : Attribute
Hereda de: Attribute

Declares the mandatory `SecurityPlane` required to execute a Mediator command or query.

Miembros (2)

  • constructorRequirePlaneAttribute
    public RequirePlaneAttribute(SecurityPlane plane)

    Initializes a new instance of the `RequirePlaneAttribute` class.

    plane: SecurityPlane
    The required security execution plane.
  • propertyPlane
    public SecurityPlane Plane { get; }

    Gets the required `SecurityPlane`.

class

SecurityMediatorServiceCollectionExtensions

Ensamblado: EricksonLopez.Security.Mediator
public static class SecurityMediatorServiceCollectionExtensions

Dependency injection registration helpers for `ZeroTrustAuthorizationBehavior<TRequest, TResponse>`.

Miembros (1)

  • methodAddZeroTrustMediatorAuthorization
    public static IServiceCollection AddZeroTrustMediatorAuthorization(this IServiceCollection services)

    Registers the open-generic `ZeroTrustAuthorizationBehavior<TRequest, TResponse>` in the service collection.

    services: this IServiceCollection
    The target service collection.

    Retorna: The same `services` instance for chaining.

class

ZeroTrustAuthorizationBehavior<TRequest, TResponse>

Ensamblado: EricksonLopez.Security.Mediator
public sealed class ZeroTrustAuthorizationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
Implementa: IPipelineBehavior<TRequest, TResponse>

Enforces fail-closed Zero-Trust authorization across Mediator commands and queries: default-deny policy verification, pre-auth token confinement, `SecurityPlane` isolation, NIST SP 800-63B `AuthenticationAssuranceLevel` checks, RBAC permissions, and `ITenantScopedRequest` boundary protection.

Notas:

Type parameters: TRequest: The request type.; TResponse: The response type.

Miembros (2)

  • constructorZeroTrustAuthorizationBehavior
    public ZeroTrustAuthorizationBehavior(IZeroTrustSecurityContext securityContext, ILogger<ZeroTrustAuthorizationBehavior<TRequest, TResponse>>? logger = null, ISecurityFailureResultFactory<TResponse>? failureFactory = null)

    Initializes a new instance of the `ZeroTrustAuthorizationBehavior<TRequest, TResponse>` class.

    securityContext: IZeroTrustSecurityContext
    The ambient Zero-Trust security context.
    logger: ILogger<ZeroTrustAuthorizationBehavior<TRequest, TResponse>>?
    Optional diagnostic logger.
    failureFactory: ISecurityFailureResultFactory<TResponse>?
    Optional AOT-safe factory converting `Error` into `TResponse`.
  • methodHandle<TNext>
    public async ValueTask<TResponse> Handle<TNext>(TRequest request, TNext next, CancellationToken cancellationToken) where TNext : struct, INext<TResponse>

    Inherits documentation from base type or interface.

    request: TRequest
    next: TNext
    cancellationToken: CancellationToken

EricksonLopez.Security.Memory#

3
class

ProtectedSecret

Ensamblado: EricksonLopez.Security
public sealed class ProtectedSecret

Encapsulates an encrypted secret payload held in memory at rest, supporting deferred, on-demand unprotection via an injected or provided `ISecretProtector`.

Miembros (6)

  • constructorProtectedSecret
    public ProtectedSecret(KeyIdentifier keyId, KeyVersion keyVersion, ReadOnlyMemory<byte> protectedBytes)

    Initializes a new instance of the `ProtectedSecret` class.

    keyId: KeyIdentifier
    The key identifier.
    keyVersion: KeyVersion
    The key version.
    protectedBytes: ReadOnlyMemory<byte>
    The encrypted envelope payload bytes.
  • methodToString
    public override string ToString()

    Inherits documentation from base type or interface.

  • methodUnprotectAsync
    public ValueTask<Result<byte[]>> UnprotectAsync(ISecretProtector protector, AuthenticatedContext expectedAssociatedData = default, CancellationToken cancellationToken = default)

    Asynchronously unprotects and decrypts this secret using the specified secret protector.

    protector: ISecretProtector
    The secret protector service.
    expectedAssociatedData: AuthenticatedContext
    The optional authenticated associated data.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a `Result<T>` containing the decrypted plaintext byte array.

    Exceptions: ArgumentNullException: `protector` is `null`

  • propertyKeyId
    public KeyIdentifier KeyId { get; }

    Gets the key identifier that encrypted this secret.

  • propertyKeyVersion
    public KeyVersion KeyVersion { get; }

    Gets the version of the key that encrypted this secret.

  • propertyProtectedBytes
    public ReadOnlyMemory<byte> ProtectedBytes { get; }

    Gets the encrypted envelope payload bytes.

class

SecretBuffer

Ensamblado: EricksonLopez.Security
public sealed class SecretBuffer : ISecretBuffer
Implementa: ISecretBuffer

Provides a high-performance, memory-scrubbing byte buffer that wipes its memory with `CryptographicOperations.ZeroMemory(Span<byte>)` when disposed. Allocates from `ArrayPool<T>.Shared` for efficiency and low GC pressure.

Miembros (12)

  • constructorSecretBuffer
    public SecretBuffer(int length)

    Initializes a new instance of the `SecretBuffer` class by renting a buffer from the array pool.

    length: int
    The required length in bytes.

    Exceptions: ArgumentOutOfRangeException: `length` is less than or equal to zero

  • methodCreateRandom
    public static SecretBuffer CreateRandom(int length)

    Creates a new `SecretBuffer` populated with cryptographically strong random bytes.

    length: int
    The number of random bytes.

    Retorna: A new `SecretBuffer`.

  • methodDispose
    public void Dispose()

    Releases the resources used by this instance.

    Zeroes out the underlying rented memory buffer upon disposal and returns it to the pool.

  • methodFixedTimeEquals
    public bool FixedTimeEquals(ReadOnlySpan<byte> other)

    Performs constant-time comparison of this secret buffer against another byte span.

    other: ReadOnlySpan<byte>
    The other byte span.

    Retorna: `true` if equal in constant time; otherwise, `false`.

  • methodFromSpan
    public static SecretBuffer FromSpan(ReadOnlySpan<byte> source)

    Creates a new `SecretBuffer` by copying bytes from a source span.

    source: ReadOnlySpan<byte>
    The source byte span.

    Retorna: A new `SecretBuffer` containing a copy of the source bytes.

    Exceptions: ArgumentException: `source` is empty

  • methodFromUtf8
    public static SecretBuffer FromUtf8(ReadOnlySpan<char> chars)

    Creates a new `SecretBuffer` by encoding the provided character span into UTF-8.

    chars: ReadOnlySpan<char>
    The character span containing sensitive text.

    Retorna: A new `SecretBuffer` containing the UTF-8 bytes.

    Exceptions: ArgumentException: `chars` is empty

  • methodGetWritableSpan
    public Span<byte> GetWritableSpan()

    Returns a writable span over the secret buffer for initial population. Access should be limited strictly to construction/initialization.

    Retorna: A writable span.

    Exceptions: ObjectDisposedException: The buffer has been disposed

  • methodToString
    public override string ToString()

    Inherits documentation from base type or interface.

  • propertyEmpty
    public static SecretBuffer Empty { get; }

    Gets a singleton instance of an empty `SecretBuffer`. Disposal of the empty singleton is a safe no-op.

  • propertyIsDisposed
    public bool IsDisposed { get; }

    Inherits documentation from base type or interface.

  • propertyLength
    public int Length { get; }

    Inherits documentation from base type or interface.

  • propertySpan
    public ReadOnlySpan<byte> Span { get; }

    Gets a read-only span over the secret buffer for zero-allocation access. Access should be bounded by a `scoped` or `using` block.

    Exceptions: ObjectDisposedException: The buffer has been disposed

class

Secret<T>

Ensamblado: EricksonLopez.Security
public sealed class Secret<T> : EricksonLopez.Security.Abstractions.Primitives.ISecret<T>
Implementa: EricksonLopez.Security.Abstractions.Primitives.ISecret<T>

Represents a typed secret value wrapper implementing `ISecret<T>` that redacts sensitive values in `ToString` and performs best-effort memory scrubbing on disposable inner values.

Notas:

Type parameters: T: The underlying secret type.

Miembros (6)

  • constructorSecret
    public Secret(T value)

    Initializes a new instance of the `Secret<T>` class.

    value: T
    The sensitive value.

    String limitation (SEC-GC-001): When `T` is `string`, `Dispose` nullifies the reference but cannot perform `ZeroMemory` on the immutable string bytes in the managed GC heap. The garbage collector may retain the string object in memory for an indeterminate period after disposal. For cryptographic secrets that require deterministic zeroization, prefer `SecretBuffer` (which uses `ArrayPool` + `ZeroMemory`) or `SecretBuffer.FromUtf8`. Exceptions: ArgumentNullException: `value` is `null`

  • methodDispose
    public void Dispose()

    Releases the resources used by this instance.

    Scrubs the underlying secret value from memory upon disposal.

  • methodToString
    public override string ToString()

    Inherits documentation from base type or interface.

  • propertyIsDisposed
    public bool IsDisposed { get; }

    Gets a value indicating whether this secret container has been disposed and its memory scrubbed.

  • propertyLength
    public int Length { get; }

    Gets the length of the secret material in bytes or characters.

  • propertyValue
    public T Value { get; }

    Gets the protected secret value.

    Exceptions: System.ObjectDisposedException: The secret container has been disposed

EricksonLopez.Security.Mfa#

12
class

Base32Encoding

Ensamblado: EricksonLopez.Security.Mfa
public static class Base32Encoding

Provides RFC 4648 Base32 encoding and decoding methods without padding for TOTP secret keys.

Miembros (4)

  • methodDecodeLenient
    public static byte[] DecodeLenient(string? base32)

    Decodes a Base32 string tolerating interior spaces, lowercase letters, and non-zero trailing padding bits, returning an empty array on invalid or empty input instead of throwing exceptions.

    base32: string?
    The Base32 encoded string.

    Retorna: The decoded byte array, or an empty array if the input is null, empty, or invalid.

  • methodFromBase32String
    public static byte[] FromBase32String(string base32)

    Decodes a Base32 string back into its original raw bytes.

    base32: string
    The Base32 encoded string.

    Retorna: The decoded byte array.

    Exceptions: ArgumentNullException: `base32` is `null`; ArgumentException: `base32` exceeds the maximum allowed length of 2048 characters; FormatException: `base32` contains an invalid Base32 character

  • methodToBase32String
    public static string ToBase32String(byte[] data)

    Encodes a byte array into a Base32 string.

    data: byte[]
    The raw bytes to encode.

    Retorna: The Base32 string representation.

    Exceptions: ArgumentNullException: `data` is `null`

  • methodTryDecode
    public static bool TryDecode(string? base32, out byte[] bytes, bool ignorePaddingBits = true)

    Attempts to decode a Base32 string (tolerating interior spaces, lowercase characters, and variable padding) without throwing exceptions.

    base32: string?
    The Base32 encoded string.
    bytes: out byte[]
    When this method returns, contains the decoded bytes, or an empty array if decoding failed.
    ignorePaddingBits: bool
    If `true`, ignores trailing non-zero padding bits and partial trailing quanta.

    Retorna: `true` if the input was decoded; otherwise, `false`.

class

DelegateTotpReplayStore

Ensamblado: EricksonLopez.Security.Mfa
public sealed class DelegateTotpReplayStore : ITotpReplayStore
Implementa: ITotpReplayStore

Provides a delegate-driven implementation of `ITotpReplayStore` to easily integrate distributed stores (such as Redis, distributed caches, or shared databases) without requiring a full subclass.

Miembros (4)

  • constructorDelegateTotpReplayStore
    public DelegateTotpReplayStore(Func<string, DateTimeOffset, CancellationToken, ValueTask<bool>> asyncHandler)

    Initializes a new instance of the `DelegateTotpReplayStore` class with an asynchronous delegate handler.

    asyncHandler: Func<string, DateTimeOffset, CancellationToken, ValueTask<bool>>
    The asynchronous delegate invoked to record replay keys.

    Exceptions: ArgumentNullException: `asyncHandler` is `null`

  • constructorDelegateTotpReplayStore
    public DelegateTotpReplayStore(Func<string, DateTimeOffset, CancellationToken, ValueTask<bool>> asyncHandler, Func<string, DateTimeOffset, bool>? syncHandler)

    Initializes a new instance of the `DelegateTotpReplayStore` class with both asynchronous and synchronous handlers.

    asyncHandler: Func<string, DateTimeOffset, CancellationToken, ValueTask<bool>>
    The asynchronous delegate invoked to record replay keys.
    syncHandler: Func<string, DateTimeOffset, bool>?
    Optional synchronous delegate invoked during synchronous verification.

    Exceptions: ArgumentNullException: `asyncHandler` is `null`

  • methodTryAdd
    public bool TryAdd(string key, DateTimeOffset expiresAt)

    Attempts to record a consumed TOTP token replay key with an expiration timestamp.

    key: string
    The unique replay key (e.g. hash of secret and time-step index).
    expiresAt: DateTimeOffset
    The timestamp at which this replay record expires.

    Retorna: `true` if the key was successfully added (not previously consumed); `false` if already consumed.

  • methodTryAddAsync
    public ValueTask<bool> TryAddAsync(string key, DateTimeOffset expiresAt, CancellationToken cancellationToken = default)

    Asynchronously attempts to record a consumed TOTP token replay key with an expiration timestamp.

    key: string
    The unique replay key (e.g. hash of secret and time-step index).
    expiresAt: DateTimeOffset
    The timestamp at which this replay record expires.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: `true` if the key was successfully added (not previously consumed); `false` if already consumed.

interface

IRecoveryCodeGenerator

Ensamblado: EricksonLopez.Security.Mfa
public interface IRecoveryCodeGenerator

Defines a contract for generating cryptographically secure emergency recovery backup codes.

Miembros (1)

  • methodGenerateCodes
    string[] GenerateCodes(int count = 10, int codeLength = 10)

    Generates a collection of unique, formatted recovery codes.

    count: int
    The number of recovery codes to generate, defaulting to 10
    codeLength: int
    The length of each code before formatting, defaulting to 10

    Retorna: An array of formatted recovery codes.

interface

ITotpReplayStore

Ensamblado: EricksonLopez.Security.Mfa
public interface ITotpReplayStore

Defines the contract for recording and verifying consumed TOTP tokens to prevent replay attacks across single-node or distributed environments.

Miembros (2)

  • methodTryAdd
    bool TryAdd(string key, DateTimeOffset expiresAt)

    Attempts to record a consumed TOTP token replay key with an expiration timestamp.

    key: string
    The unique replay key (e.g. hash of secret and time-step index).
    expiresAt: DateTimeOffset
    The timestamp at which this replay record expires.

    Retorna: `true` if the key was successfully added (not previously consumed); `false` if already consumed.

  • methodTryAddAsync
    ValueTask<bool> TryAddAsync(string key, DateTimeOffset expiresAt, CancellationToken cancellationToken = default)

    Asynchronously attempts to record a consumed TOTP token replay key with an expiration timestamp.

    key: string
    The unique replay key (e.g. hash of secret and time-step index).
    expiresAt: DateTimeOffset
    The timestamp at which this replay record expires.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: `true` if the key was successfully added (not previously consumed); `false` if already consumed.

interface

ITotpService

Ensamblado: EricksonLopez.Security.Mfa
public interface ITotpService

Defines RFC 6238 Time-Based One-Time Password (TOTP) generation and verification operations.

Miembros (4)

  • methodComputeCode
    string ComputeCode(string secretKey, DateTimeOffset timestamp, TotpOptions? options = null)

    Computes the active TOTP code for a specific timestamp.

    secretKey: string
    The Base32 encoded secret key.
    timestamp: DateTimeOffset
    The timestamp for which to compute the code.
    options: TotpOptions?
    Optional TOTP options.

    Retorna: The calculated numeric code string (e.g. "123456").

  • methodGenerateSecretKey
    byte[] GenerateSecretKey(int byteLength = 20)

    Generates a new cryptographically random Base32 encoded secret key.

    byteLength: int
    The key length in bytes (default is 20 bytes = 160 bits, recommended by RFC 4226).

    Retorna: A raw cryptographically random byte array. Consumers should format this securely or store it in an encrypted buffer.

    Exceptions: ArgumentOutOfRangeException: `byteLength` is less than 16 (128 bits minimum)

  • methodGenerateSetupInfo
    TotpSetupInfo GenerateSetupInfo(string issuer, string accountName, string? secretKey = null, TotpOptions? options = null)

    Generates the setup information (including `otpauth://` URI) for enrolling a user in an authenticator app.

    issuer: string
    The company or application name (e.g. "EricksonLopez").
    accountName: string
    The user's email or username.
    secretKey: string?
    Optional existing secret key. If null, a new key is generated.
    options: TotpOptions?
    Optional TOTP options.

    Retorna: A setup info record containing the key and URI.

  • methodVerifyCode
    bool VerifyCode(string secretKey, string code, DateTimeOffset? timestamp = null, TotpOptions? options = null)

    Determines whether the provided code matches the secret key within the allowable time drift window.

    secretKey: string
    The Base32 encoded secret key.
    code: string
    The code entered by the user.
    timestamp: DateTimeOffset?
    Optional timestamp to verify against (default is current time).
    options: TotpOptions?
    Optional TOTP options.

    Retorna: `true` if the code is valid; otherwise, `false`.

class

InMemoryTotpReplayStore

Ensamblado: EricksonLopez.Security.Mfa
public sealed class InMemoryTotpReplayStore : ITotpReplayStore
Implementa: ITotpReplayStore

Provides a default in-memory, thread-safe implementation of `ITotpReplayStore` with capacity limits and rate-limited expiration pruning.

Miembros (4)

  • constructorInMemoryTotpReplayStore
    public InMemoryTotpReplayStore(int maxCapacity = MaxCapacity, int pruneThreshold = 1000)

    Initializes a new instance of the `InMemoryTotpReplayStore` class.

    maxCapacity: int
    Maximum capacity of consumed codes retained in memory.
    pruneThreshold: int
    Threshold count beyond which routine expiration pruning runs.
  • methodTryAdd
    public bool TryAdd(string key, DateTimeOffset expiresAt)

    Attempts to record a consumed TOTP token replay key with an expiration timestamp.

    key: string
    The unique replay key (e.g. hash of secret and time-step index).
    expiresAt: DateTimeOffset
    The timestamp at which this replay record expires.

    Retorna: `true` if the key was successfully added (not previously consumed); `false` if already consumed.

  • methodTryAddAsync
    public ValueTask<bool> TryAddAsync(string key, DateTimeOffset expiresAt, CancellationToken cancellationToken = default)

    Asynchronously attempts to record a consumed TOTP token replay key with an expiration timestamp.

    key: string
    The unique replay key (e.g. hash of secret and time-step index).
    expiresAt: DateTimeOffset
    The timestamp at which this replay record expires.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: `true` if the key was successfully added (not previously consumed); `false` if already consumed.

  • fieldMaxCapacity
    public const int MaxCapacity

    Defines the default maximum capacity of consumed codes retained in memory.

class

RecoveryCodeGenerator

Ensamblado: EricksonLopez.Security.Mfa
public sealed class RecoveryCodeGenerator : IRecoveryCodeGenerator
Implementa: IRecoveryCodeGenerator

Generates cryptographically secure, alphanumeric emergency recovery backup codes.

Notas:

Recovery codes returned by `GenerateCodes` are in plaintext and must be hashed before storage. Use `HashCode(string)` to obtain the hash for persistence and `VerifyCode(string, string)` to verify a user-supplied recovery code against the stored hash in constant time, preventing timing oracles. Recommended flow: - Call `GenerateCodes` and display all codes to the user once. - For each code, call `HashCode` and store the resulting hash. - When a user presents a recovery code, call `VerifyCode` against each stored hash. - Delete (mark as used) the matched hash immediately after successful verification.

Miembros (3)

  • methodGenerateCodes
    public string[] GenerateCodes(int count = 10, int codeLength = 10)

    Generates a collection of unique, formatted recovery codes.

    count: int
    The number of recovery codes to generate (default is 10).
    codeLength: int
    The length of each code before formatting (default is 10).

    Retorna: An array of formatted recovery codes (e.g. `XXXX-XXXX-XX`).

    Exceptions: ArgumentOutOfRangeException: `count` is less than or equal to zero, or `codeLength` is less than 8

  • methodHashCode
    public static string HashCode(string plaintextCode)

    Computes a SHA-256 hash of the recovery code for secure storage. Store this hash instead of the plaintext code.

    plaintextCode: string
    The plaintext recovery code to hash.

    Retorna: A lowercase hex string of the SHA-256 hash (64 characters).

    AUTH-010 fix: recovery codes must be stored as hashes, not plaintext. SHA-256 is appropriate here because recovery codes are high-entropy random values (not passwords), so a fast hash without salt is sufficient — the entropy of the code itself provides the necessary brute-force resistance. Exceptions: ArgumentException: `plaintextCode` is `null` or whitespace

  • methodVerifyCode
    public static bool VerifyCode(string plaintextCode, string storedHash)

    Verifies a user-supplied recovery code against a stored hash in constant time, preventing timing oracle attacks.

    plaintextCode: string
    The recovery code entered by the user.
    storedHash: string
    The SHA-256 hash previously stored via `HashCode`.

    Retorna: `true` if the code matches the stored hash; `false` otherwise.

    AUTH-010 fix: uses `CryptographicOperations.FixedTimeEquals` to prevent timing-based enumeration of which recovery codes are valid.

class

SecurityMfaServiceCollectionExtensions

Ensamblado: EricksonLopez.Security.Mfa
public static class SecurityMfaServiceCollectionExtensions

Provides extension methods for registering multi-factor authentication and TOTP services into the service collection.

Miembros (3)

  • methodAddDistributedTotpReplayStore
    public static IServiceCollection AddDistributedTotpReplayStore(this IServiceCollection services, Func<string, DateTimeOffset, System.Threading.CancellationToken, System.Threading.Tasks.ValueTask<bool>> asyncHandler, Func<string, DateTimeOffset, bool>? syncHandler = null)

    Overrides the default in-memory TOTP replay store with a delegate-based distributed store handler.

    services: this IServiceCollection
    The service collection to configure.
    asyncHandler: Func<string, DateTimeOffset, System.Threading.CancellationToken, System.Threading.Tasks.ValueTask<bool>>
    The asynchronous delegate invoked to record replay keys.
    syncHandler: Func<string, DateTimeOffset, bool>?
    Optional synchronous delegate invoked during synchronous verification.

    Retorna: The same service collection instance for method chaining.

    Exceptions: ArgumentNullException: `services` or `asyncHandler` is `null`

  • methodAddDistributedTotpReplayStore<TStore>
    public static IServiceCollection AddDistributedTotpReplayStore<TStore>(this IServiceCollection services) where TStore : class, ITotpReplayStore

    Overrides the default in-memory TOTP replay store with a custom distributed store implementation.

    services: this IServiceCollection
    The service collection to configure.

    Retorna: The same service collection instance for method chaining.

    Type parameters: TStore: The distributed store type implementing `ITotpReplayStore`. Exceptions: ArgumentNullException: `services` is `null`

  • methodAddSecurityMfa
    public static IServiceCollection AddSecurityMfa(this IServiceCollection services)

    Registers the `ITotpService` implementation into the service collection.

    services: this IServiceCollection
    The service collection to configure.

    Retorna: The same service collection instance for method chaining.

    Exceptions: ArgumentNullException: `services` is `null`

enum

TotpHashAlgorithm

Ensamblado: EricksonLopez.Security.Mfa
public enum TotpHashAlgorithm

Specifies the cryptographic hash algorithm for TOTP code generation.

Miembros (3)

  • fieldSha1
    Sha1 = 0

    Specifies HMAC-SHA1 (default standard algorithm used by most authenticator apps).

  • fieldSha256
    Sha256 = 1

    Specifies HMAC-SHA256 for enhanced security.

  • fieldSha512
    Sha512 = 2

    Specifies HMAC-SHA512 for maximum security.

class

TotpOptions

Ensamblado: EricksonLopez.Security.Mfa
public sealed class TotpOptions

Specifies configuration options for TOTP code generation and verification.

Miembros (5)

  • propertyAlgorithm
    public TotpHashAlgorithm Algorithm { get; set; }

    Gets or sets the hash algorithm. Default is `TotpHashAlgorithm.Sha1`.

  • propertyAllowedDriftSteps
    public int AllowedDriftSteps { get; set; }

    Gets or sets the number of drift time steps allowed before/after the current time step. Default is 1 (±30 seconds).

  • propertyDigits
    public int Digits { get; set; }

    Gets or sets the number of digits in the generated code (typically 6 or 8). Default is 6.

  • propertyPeriodSeconds
    public int PeriodSeconds { get; set; }

    Gets or sets the time step period in seconds. Default is 30 seconds.

  • propertyPreventReplay
    public bool PreventReplay { get; set; }

    Gets or sets a value indicating whether to prevent replay attacks by rejecting already consumed codes within their validity time step window (RFC 6238 Section 5.2). Default is `true`.

class

TotpService

Ensamblado: EricksonLopez.Security.Mfa
public sealed class TotpService : ITotpService
Implementa: ITotpService

Provides RFC 6238 Time-Based One-Time Password (TOTP) generation and constant-time verification services.

Notas:

⚠️ SEC-001 — Multi-node deployment limitation (replay protection). This implementation stores consumed TOTP codes in an in-process `Concurrent.ConcurrentDictionary<TKey, TValue>`. This provides correct replay protection only on a single-node deployment. In a horizontally-scaled environment (Kubernetes pods, Azure App Service with multiple instances, behind a load balancer, or any multi-process setup), each process maintains its own independent in-memory store. A TOTP code verified on Node A can be immediately replayed against Node B, Node C, etc., because they have no shared state. For multi-node deployments, you must implement a distributed replay cache using a shared backend such as Redis (`IDistributedCache`), a database, or any other cross-process store. The recommended pattern is: - Use a time-bounded distributed cache key: `{sha256(secretKey)}:{timeStep}` - Use `SET NX EX` (Redis) or equivalent atomic set-if-not-exists for thread-safety. - Set the TTL to `(AllowedDriftSteps + 2) × PeriodSeconds` seconds. Single-node deployments: Provides out-of-the-box replay protection for single-instance applications. The in-memory cache is thread-safe, rate-limited to prevent DoS, and handles clock drift correctly per RFC 6238.

Miembros (7)

  • constructorTotpService
    public TotpService(TimeProvider? timeProvider = null, ITotpReplayStore? replayStore = null)

    Initializes a new instance of the `TotpService` class.

    timeProvider: TimeProvider?
    Optional time provider for testing time drift.
    replayStore: ITotpReplayStore?
    Optional distributed or custom replay store for multi-node deployments.
  • methodComputeCode
    public string ComputeCode(string secretKey, DateTimeOffset timestamp, TotpOptions? options = null)

    Computes the active TOTP code for a specific timestamp.

    secretKey: string
    The Base32 encoded secret key.
    timestamp: DateTimeOffset
    The timestamp for which to compute the code.
    options: TotpOptions?
    Optional TOTP options.

    Retorna: The calculated numeric code string (e.g. "123456").

  • methodComputeHotpCode
    public static string ComputeHotpCode(ReadOnlySpan<byte> keyBytes, long counter, int digits = 6, TotpHashAlgorithm algorithm = TotpHashAlgorithm.Sha1)

    Computes an RFC 4226 HMAC-Based One-Time Password (HOTP) code for a raw secret key and 64-bit counter.

    keyBytes: ReadOnlySpan<byte>
    The raw secret key bytes.
    counter: long
    The 8-byte counter value (or TOTP time-step index).
    digits: int
    The number of digits in the generated OTP (6 to 9, default 6).
    algorithm: TotpHashAlgorithm
    The HMAC hash algorithm (default `TotpHashAlgorithm.Sha1`).

    Retorna: The zero-padded numeric OTP string.

  • methodGenerateSecretKey
    public byte[] GenerateSecretKey(int byteLength = 20)

    Generates a new cryptographically random Base32 encoded secret key.

    byteLength: int
    The key length in bytes (default is 20 bytes = 160 bits, recommended by RFC 4226).

    Retorna: A raw cryptographically random byte array. Consumers should format this securely or store it in an encrypted buffer.

    Exceptions: ArgumentOutOfRangeException: `byteLength` is less than 16 (128 bits minimum)

  • methodGenerateSetupInfo
    public TotpSetupInfo GenerateSetupInfo(string issuer, string accountName, string? secretKey = null, TotpOptions? options = null)

    Generates the setup information (including `otpauth://` URI) for enrolling a user in an authenticator app.

    issuer: string
    The company or application name (e.g. "EricksonLopez").
    accountName: string
    The user's email or username.
    secretKey: string?
    Optional existing secret key. If null, a new key is generated.
    options: TotpOptions?
    Optional TOTP options.

    Retorna: A setup info record containing the key and URI.

  • methodVerifyCode
    public bool VerifyCode(string secretKey, string code, DateTimeOffset? timestamp = null, TotpOptions? options = null)

    Determines whether the provided code matches the secret key within the allowable time drift window.

    secretKey: string
    The Base32 encoded secret key.
    code: string
    The code entered by the user.
    timestamp: DateTimeOffset?
    Optional timestamp to verify against (default is current time).
    options: TotpOptions?
    Optional TOTP options.

    Retorna: `true` if the code is valid; otherwise, `false`.

  • methodVerifyCodeAsync
    public async System.Threading.Tasks.ValueTask<bool> VerifyCodeAsync(string secretKey, string code, DateTimeOffset? timestamp = null, TotpOptions? options = null, CancellationToken cancellationToken = default)

    Asynchronously determines whether the provided code matches the secret key within the allowable time drift window, supporting distributed replay stores.

    secretKey: string
    The Base32 encoded secret key.
    code: string
    The code entered by the user.
    timestamp: DateTimeOffset?
    Optional timestamp to verify against (default is current time).
    options: TotpOptions?
    Optional TOTP options.
    cancellationToken: CancellationToken
    A token to monitor for cancellation requests.

    Retorna: `true` if the code is valid; otherwise, `false`.

record

TotpSetupInfo

Ensamblado: EricksonLopez.Security.Mfa
public sealed record TotpSetupInfo(string SecretKey, string FormattedSecretKey, string AuthenticatorUri)

Encapsulates the configuration details and URI required to enroll a user in TOTP multi-factor authentication.

Miembros (4)

  • constructorTotpSetupInfo
    public TotpSetupInfo(string SecretKey, string FormattedSecretKey, string AuthenticatorUri)

    Initializes a new instance of TotpSetupInfo.

    SecretKey: string
    The Base32 encoded secret key.
    FormattedSecretKey: string
    The secret key formatted in 4-character chunks for manual entry.
    AuthenticatorUri: string
    The standard `otpauth://` URI for generating QR codes.
  • propertyAuthenticatorUri
    public string AuthenticatorUri { get; init; }

    The standard `otpauth://` URI for generating QR codes.

  • propertyFormattedSecretKey
    public string FormattedSecretKey { get; init; }

    The secret key formatted in 4-character chunks for manual entry.

  • propertySecretKey
    public string SecretKey { get; init; }

    The Base32 encoded secret key.

EricksonLopez.Security.Network#

13
interface

ISafeDnsResolver

Ensamblado: EricksonLopez.Security.Network
public interface ISafeDnsResolver

Defines a DNS resolver that validates resolved IP addresses against SSRF policies.

Miembros (1)

  • methodResolveAndValidateAsync
    Task<Result<IPAddress[]>> ResolveAndValidateAsync(string host, CancellationToken cancellationToken = default)

    Resolves the host name to IP addresses and validates that all addresses comply with SSRF protection policies.

    host: string
    The host name or IP string to resolve and validate.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a successful result with the valid IP addresses, or an error describing the SSRF violation.

interface

ITenantIpAccessEvaluator

Ensamblado: EricksonLopez.Security.Network
public interface ITenantIpAccessEvaluator

Evaluates client IPv4/IPv6 addresses against per-tenant CIDR allowlists and blocklists using strict `Deny-Overrides` precedence.

Miembros (2)

  • methodEvaluate
    IpAccessDecision Evaluate(IPAddress? clientIp, IReadOnlyList<TenantIpRule> rules, IpAccessDefaultBehavior defaultBehavior = IpAccessDefaultBehavior.AllowWhenNoAllowRules, DateTimeOffset? evaluationTimeUtc = null)

    Evaluates `clientIp` against `rules` using `Deny-Overrides` precedence.

    clientIp: IPAddress?
    rules: IReadOnlyList<TenantIpRule>
    defaultBehavior: IpAccessDefaultBehavior
    evaluationTimeUtc: DateTimeOffset?
  • methodEvaluate
    IpAccessDecision Evaluate(string? clientIpString, IReadOnlyList<TenantIpRule> rules, IpAccessDefaultBehavior defaultBehavior = IpAccessDefaultBehavior.AllowWhenNoAllowRules, DateTimeOffset? evaluationTimeUtc = null)

    Parses `clientIpString` and evaluates it against `rules` using `Deny-Overrides` precedence.

    clientIpString: string?
    rules: IReadOnlyList<TenantIpRule>
    defaultBehavior: IpAccessDefaultBehavior
    evaluationTimeUtc: DateTimeOffset?
record

IpAccessDecision

Ensamblado: EricksonLopez.Security.Network
public readonly record struct IpAccessDecision(bool IsAllowed, IpAccessDecisionReason Reason, string? MatchedRuleId, IpAddressRange? MatchedRange)

Represents the deterministic outcome of evaluating a client IP against tenant IP access rules.

Miembros (5)

  • constructorIpAccessDecision
    public IpAccessDecision(bool IsAllowed, IpAccessDecisionReason Reason, string? MatchedRuleId = null, IpAddressRange? MatchedRange = null)

    Initializes a new instance of IpAccessDecision.

    IsAllowed: bool
    Whether the client IP is permitted.
    Reason: IpAccessDecisionReason
    Structured reason explaining the decision.
    MatchedRuleId: string?
    Identifier of the rule that triggered the decision, if any.
    MatchedRange: IpAddressRange?
    CIDR range of the rule that triggered the decision, if any.
  • propertyIsAllowed
    public bool IsAllowed { get; init; }

    Whether the client IP is permitted.

  • propertyMatchedRange
    public IpAddressRange? MatchedRange { get; init; }

    CIDR range of the rule that triggered the decision, if any.

  • propertyMatchedRuleId
    public string? MatchedRuleId { get; init; }

    Identifier of the rule that triggered the decision, if any.

  • propertyReason
    public IpAccessDecisionReason Reason { get; init; }

    Structured reason explaining the decision.

enum

IpAccessDecisionReason

Ensamblado: EricksonLopez.Security.Network
public enum IpAccessDecisionReason

Explains why a client IP address was allowed or denied by `TenantIpAccessEvaluator`.

Miembros (5)

  • fieldAllowedByDefaultNoAllowRules
    AllowedByDefaultNoAllowRules = 0

    No active allow rules were configured and `IpAccessDefaultBehavior.AllowWhenNoAllowRules` applied.

  • fieldAllowedByMatchingRule
    AllowedByMatchingRule = 1

    Matched an active `IpAccessEffect.Allow` rule with no matching `IpAccessEffect.Deny` rule.

  • fieldDeniedByMatchingRule
    DeniedByMatchingRule = 2

    Blocked because an active `IpAccessEffect.Deny` rule matched (`Deny-Overrides` precedence).

  • fieldDeniedInvalidClientIp
    DeniedInvalidClientIp = 4

    Blocked because the supplied client IP address was null, empty, or malformed.

  • fieldDeniedNoMatchingAllowRule
    DeniedNoMatchingAllowRule = 3

    Blocked because active allowlist rules exist (or `IpAccessDefaultBehavior.DenyByDefault` is active) and none matched.

enum

IpAccessDefaultBehavior

Ensamblado: EricksonLopez.Security.Network
public enum IpAccessDefaultBehavior

Controls default evaluation behavior when no active `IpAccessEffect.Allow` rules are configured for a tenant.

Miembros (2)

  • fieldAllowWhenNoAllowRules
    AllowWhenNoAllowRules = 0

    Permits traffic when no active allowlist rules exist (unless matched by an active `IpAccessEffect.Deny` rule).

  • fieldDenyByDefault
    DenyByDefault = 1

    Denies all traffic unless matched by at least one active `IpAccessEffect.Allow` rule.

enum

IpAccessEffect

Ensamblado: EricksonLopez.Security.Network
public enum IpAccessEffect

Defines the access control effect of a tenant IP / CIDR rule.

Miembros (2)

  • fieldAllow
    Allow = 0

    Explicitly permits requests originating from the matching IP or CIDR network.

  • fieldDeny
    Deny = 1

    Explicitly blocks requests originating from the matching IP or CIDR network (takes precedence over `Allow`).

struct

IpAddressRange

Ensamblado: EricksonLopez.Security.Network
public readonly struct IpAddressRange : IEquatable<IpAddressRange>
Implementa: IEquatable<IpAddressRange>

Represents a contiguous range of IP addresses defined by an IP network prefix and CIDR mask.

Miembros (13)

  • constructorIpAddressRange
    public IpAddressRange(IPAddress baseAddress, int prefixLength)

    Initializes a new instance of the `IpAddressRange` struct from an IP address and CIDR prefix length.

    baseAddress: IPAddress
    The base IP address of the network.
    prefixLength: int
    The CIDR prefix length (0-32 for IPv4, 0-128 for IPv6).

    Exceptions: ArgumentNullException: `baseAddress` is `null`; ArgumentOutOfRangeException: `prefixLength` is invalid for the address family

  • methodContains
    public bool Contains(IPAddress address)

    Determines whether the specified `IPAddress` falls within this network range.

    address: IPAddress
    The IP address to evaluate.

    Retorna: `true` if the address is contained in this range; otherwise, `false`.

  • methodEquals
    public bool Equals(IpAddressRange other)

    Inherits documentation from base type or interface.

    other: IpAddressRange
  • methodEquals
    public override bool Equals(object? obj)

    Inherits documentation from base type or interface.

    obj: object?
  • methodGetHashCode
    public override int GetHashCode()

    Inherits documentation from base type or interface.

  • methodParse
    public static IpAddressRange Parse(string cidrOrAddress)

    Parses a CIDR string (e.g., "10.0.0.0/8" or "192.168.1.1") into an `IpAddressRange`.

    cidrOrAddress: string
    The CIDR or single IP address string.

    Retorna: The parsed `IpAddressRange`.

    Exceptions: ArgumentNullException: `cidrOrAddress` is `null`; FormatException: The format of the string is invalid

  • methodToString
    public override string ToString()

    Inherits documentation from base type or interface.

  • methodoperator !=
    public static bool operator !=(IpAddressRange left, IpAddressRange right)

    Determines whether two `IpAddressRange` instances represent different network ranges.

    left: IpAddressRange
    The first network range to compare.
    right: IpAddressRange
    The second network range to compare.

    Retorna: `true` if both instances represent different network ranges; otherwise, `false`.

  • methodoperator ==
    public static bool operator ==(IpAddressRange left, IpAddressRange right)

    Determines whether two `IpAddressRange` instances represent the same network range.

    left: IpAddressRange
    The first network range to compare.
    right: IpAddressRange
    The second network range to compare.

    Retorna: `true` if both instances represent the same network range; otherwise, `false`.

  • propertyAddressFamily
    public AddressFamily AddressFamily { get; }

    Gets the address family (`AddressFamily.InterNetwork` or `AddressFamily.InterNetworkV6`).

  • propertyIsDefault
    public bool IsDefault { get; }

    Gets a value indicating whether the current instance is the default uninitialized instance.

  • propertyNetworkAddress
    public IPAddress? NetworkAddress { get; }

    Gets the base network address of this range, or `null` if uninitialized.

  • propertyPrefixLength
    public int PrefixLength { get; }

    Gets the CIDR prefix length (0-32 for IPv4, 0-128 for IPv6).

class

SafeDnsResolver

Ensamblado: EricksonLopez.Security.Network
public sealed class SafeDnsResolver : ISafeDnsResolver
Implementa: ISafeDnsResolver

Provides DNS resolution with validation against prohibited private network ranges and cloud metadata services.

Miembros (2)

  • constructorSafeDnsResolver
    public SafeDnsResolver(SsrfProtectionOptions? options = null, Func<string, CancellationToken, Task<IPAddress[]>>? dnsLookup = null)

    Initializes a new instance of the `SafeDnsResolver` class.

    options: SsrfProtectionOptions?
    SSRF protection options.
    dnsLookup: Func<string, CancellationToken, Task<IPAddress[]>>?
    Optional DNS lookup delegate for testing and simulation.
  • methodResolveAndValidateAsync
    public async Task<Result<IPAddress[]>> ResolveAndValidateAsync(string host, CancellationToken cancellationToken = default)

    Resolves the host name to IP addresses and validates that all addresses comply with SSRF protection policies.

    host: string
    The host name or IP string to resolve and validate.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a successful result with the valid IP addresses, or an error describing the SSRF violation.

class

SafeHttpClientFactory

Ensamblado: EricksonLopez.Security.Network
public static class SafeHttpClientFactory

Provides factory methods for creating pre-configured, SSRF-safe `HttpClient` instances.

Miembros (1)

  • methodCreateClient
    public static HttpClient CreateClient(Action<SsrfProtectionOptions>? configure = null)

    Creates a new `HttpClient` instance configured with strict SSRF protections.

    configure: Action<SsrfProtectionOptions>?
    Optional delegate to configure SSRF protection options.

    Retorna: A configured `HttpClient` instance.

class

SafeSocketsHttpHandler

Ensamblado: EricksonLopez.Security.Network
public sealed class SafeSocketsHttpHandler : HttpMessageHandler
Hereda de: HttpMessageHandler

Provides a high-performance `HttpMessageHandler` that enforces strict SSRF protections, prevents DNS rebinding, and blocks outgoing connections to private networks and cloud metadata.

Miembros (1)

  • constructorSafeSocketsHttpHandler
    public SafeSocketsHttpHandler(ISafeDnsResolver? resolver = null, SsrfProtectionOptions? options = null)

    Initializes a new instance of the `SafeSocketsHttpHandler` class.

    resolver: ISafeDnsResolver?
    Optional custom safe DNS resolver.
    options: SsrfProtectionOptions?
    Optional SSRF protection options.
class

SsrfProtectionOptions

Ensamblado: EricksonLopez.Security.Network
public sealed class SsrfProtectionOptions

Specifies configuration options for Server-Side Request Forgery (SSRF) prevention.

Miembros (8)

  • propertyAllowedHostnames
    public ISet<string> AllowedHostnames { get; }

    Gets the set of allowed hostnames (e.g., "api.partner.com").

  • propertyAllowedRanges
    public IList<IpAddressRange> AllowedRanges { get; }

    Gets the list of explicitly allowed IP address ranges that override blocked ranges.

  • propertyBlockCloudMetadata
    public bool BlockCloudMetadata { get; set; }

    Gets or sets a value indicating whether to block well-known cloud metadata hostnames and IPs. Default is `true`.

  • propertyBlockedRanges
    public IList<IpAddressRange> BlockedRanges { get; }

    Gets the list of custom prohibited IP address ranges in addition to defaults.

  • propertyMaxRedirects
    public int MaxRedirects { get; set; }

    Gets or sets the maximum number of automatic redirects allowed. Each redirect target is validated against SSRF rules. Default is 5.

  • propertyRequireHttps
    public bool RequireHttps { get; set; }

    Gets or sets a value indicating whether HTTPS is required for all outgoing requests. Default is `true`.

  • propertyRestrictToAllowedHostnames
    public bool RestrictToAllowedHostnames { get; set; }

    Gets or sets a value indicating whether requests must be strictly restricted to `AllowedHostnames` when the set contains entries. When `true`, unlisted hosts and direct IPs are rejected.

  • fieldDefaultBlockedRanges
    public static readonly IReadOnlyList<IpAddressRange> DefaultBlockedRanges

    Gets the list of default prohibited IP address ranges (RFC 1918, loopbacks, link-local, cloud metadata).

class

TenantIpAccessEvaluator

Ensamblado: EricksonLopez.Security.Network
public sealed class TenantIpAccessEvaluator : ITenantIpAccessEvaluator
Implementa: ITenantIpAccessEvaluator

Stateless, thread-safe, Zero-Trust CIDR evaluator enforcing strict `Deny-Overrides` precedence across IPv4, IPv6, and IPv4-mapped IPv6 addresses.

Miembros (3)

  • methodEvaluate
    public IpAccessDecision Evaluate(IPAddress? clientIp, IReadOnlyList<TenantIpRule> rules, IpAccessDefaultBehavior defaultBehavior = IpAccessDefaultBehavior.AllowWhenNoAllowRules, DateTimeOffset? evaluationTimeUtc = null)

    Evaluates `clientIp` against `rules` using `Deny-Overrides` precedence.

    clientIp: IPAddress?
    rules: IReadOnlyList<TenantIpRule>
    defaultBehavior: IpAccessDefaultBehavior
    evaluationTimeUtc: DateTimeOffset?
  • methodEvaluate
    public IpAccessDecision Evaluate(string? clientIpString, IReadOnlyList<TenantIpRule> rules, IpAccessDefaultBehavior defaultBehavior = IpAccessDefaultBehavior.AllowWhenNoAllowRules, DateTimeOffset? evaluationTimeUtc = null)

    Evaluates `clientIp` against `rules` using `Deny-Overrides` precedence.

    clientIpString: string?
    rules: IReadOnlyList<TenantIpRule>
    defaultBehavior: IpAccessDefaultBehavior
    evaluationTimeUtc: DateTimeOffset?
  • propertyInstance
    public static TenantIpAccessEvaluator Instance { get; }

    Gets a shared singleton instance of `TenantIpAccessEvaluator`.

record

TenantIpRule

Ensamblado: EricksonLopez.Security.Network
public sealed record TenantIpRule(string RuleId, IpAddressRange Range, IpAccessEffect Effect, DateTimeOffset? ExpiresAtUtc, bool IsEnabled, string? Description)

Represents an immutable per-tenant IPv4 or IPv6 CIDR access control rule.

Miembros (9)

  • constructorTenantIpRule
    public TenantIpRule(string RuleId, IpAddressRange Range, IpAccessEffect Effect, DateTimeOffset? ExpiresAtUtc = null, bool IsEnabled = true, string? Description = null)

    Initializes a new instance of TenantIpRule.

    RuleId: string
    Unique identifier of the policy rule.
    Range: IpAddressRange
    Parsed IPv4 or IPv6 CIDR range.
    Effect: IpAccessEffect
    Whether the rule allows or denies matching addresses.
    ExpiresAtUtc: DateTimeOffset?
    Optional UTC expiration timestamp after which the rule is ignored.
    IsEnabled: bool
    Whether the rule is currently active.
    Description: string?
    Optional human-readable audit description.
  • methodCreate
    public static Result<TenantIpRule> Create(string ruleId, string? ipOrCidr, IpAccessEffect effect, DateTimeOffset? expiresAtUtc = null, bool isEnabled = true, string? description = null)

    Creates a validated `TenantIpRule` from a single IP or CIDR notation string.

    ruleId: string
    Unique rule identifier.
    ipOrCidr: string?
    Single IPv4/IPv6 address or CIDR range (e.g., `"203.0.113.0/24"`, `"2001:db8::/32"`).
    effect: IpAccessEffect
    Rule access effect.
    expiresAtUtc: DateTimeOffset?
    Optional UTC expiration timestamp.
    isEnabled: bool
    Whether the rule is active.
    description: string?
    Optional audit description.

    Retorna: A `Result<TenantIpRule>` containing the parsed rule or a validation error.

  • methodIsActiveAt
    public bool IsActiveAt(DateTimeOffset asOfUtc)

    Determines whether this rule is active at `asOfUtc`.

    asOfUtc: DateTimeOffset
  • propertyDescription
    public string? Description { get; init; }

    Optional human-readable audit description.

  • propertyEffect
    public IpAccessEffect Effect { get; init; }

    Whether the rule allows or denies matching addresses.

  • propertyExpiresAtUtc
    public DateTimeOffset? ExpiresAtUtc { get; init; }

    Optional UTC expiration timestamp after which the rule is ignored.

  • propertyIsEnabled
    public bool IsEnabled { get; init; }

    Whether the rule is currently active.

  • propertyRange
    public IpAddressRange Range { get; init; }

    Parsed IPv4 or IPv6 CIDR range.

  • propertyRuleId
    public string RuleId { get; init; }

    Unique identifier of the policy rule.

EricksonLopez.Security.OpenTelemetry#

1
class

SecurityOpenTelemetryExtensions

Ensamblado: EricksonLopez.Security.OpenTelemetry
public static class SecurityOpenTelemetryExtensions

Provides extension methods for registering EricksonLopez.Security instrumentation in OpenTelemetry tracing and metrics pipelines.

Notas:

Example:

// Tracing
builder.Services.AddOpenTelemetry()
    .WithTracing(tracing => tracing
        .AddEricksonLopezSecurityInstrumentation()
        .AddOtlpExporter());

// Metrics
builder.Services.AddOpenTelemetry()
    .WithMetrics(metrics => metrics
        .AddEricksonLopezSecurityInstrumentation()
        .AddOtlpExporter());

Miembros (2)

  • methodAddEricksonLopezSecurityInstrumentation
    public static MeterProviderBuilder AddEricksonLopezSecurityInstrumentation(this MeterProviderBuilder builder)

    Subscribes the EricksonLopez.Security `SecurityMeter` to the OpenTelemetry metrics pipeline.

    builder: this MeterProviderBuilder
    The meter provider builder to configure.

    Retorna: The configured `MeterProviderBuilder` instance.

    Exceptions: ArgumentNullException: `builder` is `null`

  • methodAddEricksonLopezSecurityInstrumentation
    public static TracerProviderBuilder AddEricksonLopezSecurityInstrumentation(this TracerProviderBuilder builder)

    Subscribes the EricksonLopez.Security `SecurityActivitySource` to the OpenTelemetry tracing pipeline.

    builder: this TracerProviderBuilder
    The tracer provider builder to configure.

    Retorna: The configured `TracerProviderBuilder` instance.

    Exceptions: ArgumentNullException: `builder` is `null`

EricksonLopez.Security.Passwords#

4
class

Argon2idPasswordHasher

Ensamblado: EricksonLopez.Security
public sealed class Argon2idPasswordHasher : IPasswordHasher, IDisposable
Implementa: IDisposable, IPasswordHasher

Provides password hashing that produces and verifies hashes encoded in the Argon2id modular crypt format (`$argon2id$v=19$m=<mem>,t=<iters>,p=<parallelism>$<salt>$<hash>`).

Miembros (15)

  • constructorArgon2idPasswordHasher
    public Argon2idPasswordHasher(int memorySizeKb = 65536, int iterations = 3, int parallelism = 4, int saltSizeBytes = 16)

    Initializes a new instance of the `Argon2idPasswordHasher` class with the specified cost parameters.

    memorySizeKb: int
    The memory cost in kibibytes (KiB). Must be between 1024 and 65536.
    iterations: int
    The time cost in iterations. Must be between 1 and 10.
    parallelism: int
    The degree of parallelism. Must be between 1 and 16.
    saltSizeBytes: int
    The size of the random salt in bytes. Must be between 8 and 64.

    Exceptions: ArgumentOutOfRangeException: Any parameter is outside its permitted range

  • methodDispose
    public void Dispose()

    Disposes the underlying password hasher resources.

  • methodHashPassword
    public string HashPassword(ReadOnlySpan<char> password)

    Computes a cryptographically salted and parameterized password hash for the specified password.

    password: ReadOnlySpan<char>
    The plaintext password character span. Must not exceed 256 characters.

    Retorna: A standardized, self-describing password hash string.

    Exceptions: ArgumentOutOfRangeException: `password` length exceeds 256 characters

  • methodNeedsRehash
    public bool NeedsRehash(string hashedPassword)

    Determines whether the given stored password hash requires rehashing due to parameter updates or algorithm evolution.

    hashedPassword: string
    The stored hash string to evaluate

    Retorna: `true` if the hash should be regenerated with current parameters; otherwise, `false`.

  • methodVerifyPassword
    public PasswordVerificationResult VerifyPassword(ReadOnlySpan<char> password, string hashedPassword)

    Verifies a plaintext password against a stored hashed password using constant-time evaluation.

    password: ReadOnlySpan<char>
    The candidate password character span to verify
    hashedPassword: string
    The stored hashed password string to evaluate

    Retorna: A `PasswordVerificationResult` indicating success, success with rehash required, or failure.

  • propertyAlgorithm
    public PasswordHashAlgorithm Algorithm { get; }

    Gets the primary password hashing algorithm implemented by this instance.

  • propertyIsMemoryHard
    public static bool IsMemoryHard { get; }

    Gets a value indicating whether the underlying key derivation function is memory-hard.

  • propertySubstrateDescription
    public static string SubstrateDescription { get; }

    Gets the cryptographic substrate name backing this hasher.

  • fieldDefault
    public static readonly Argon2idPasswordHasher Default

    Gets the default singleton instance configured with 64 MB memory, 3 time-cost iterations, and 4 parallelism lanes.

  • fieldMaxAllowedMemoryCost
    public const int MaxAllowedMemoryCost

    Maximum memory-cost parameter (in KiB) accepted in verification (64 MiB) to prevent memory exhaustion DoS.

  • fieldMaxAllowedParallelism
    public const int MaxAllowedParallelism

    Maximum degree of parallelism accepted in verification.

  • fieldMaxAllowedTimeCost
    public const int MaxAllowedTimeCost

    Maximum time-cost iterations parameter accepted in verification.

  • fieldMinAllowedMemoryCost
    public const int MinAllowedMemoryCost

    Minimum memory-cost parameter (in KiB) accepted in verification (1 MiB).

  • fieldMinAllowedParallelism
    public const int MinAllowedParallelism

    Minimum degree of parallelism accepted in verification.

  • fieldMinAllowedTimeCost
    public const int MinAllowedTimeCost

    Minimum time-cost iterations parameter accepted in verification.

class

CompositePasswordHasher

Ensamblado: EricksonLopez.Security
public sealed class CompositePasswordHasher : IPasswordHasher, ISimplePasswordHasher
Implementa: IPasswordHasher, ISimplePasswordHasher

Provides a composite password hasher and verifier that transparently inspects modular crypt hash prefixes, delegates verification to the matching algorithm engine, and signals when a legacy hash requires transparent rehashing to the active primary policy upon successful authentication.

Miembros (5)

  • constructorCompositePasswordHasher
    public CompositePasswordHasher(IPasswordHasher? primaryHasher = null, IEnumerable<IPasswordHasher>? additionalHashers = null)

    Initializes a new instance of the `CompositePasswordHasher` class.

    primaryHasher: IPasswordHasher?
    The primary password hasher for new hash generation.
    additionalHashers: IEnumerable<IPasswordHasher>?
    The optional collection of legacy or additional password hashers.
  • methodHashPassword
    public string HashPassword(ReadOnlySpan<char> password)

    Computes a cryptographically salted and parameterized password hash for the specified password.

    password: ReadOnlySpan<char>
    The plaintext password character span. Must not exceed 256 characters.

    Retorna: A standardized, self-describing password hash string.

    Exceptions: ArgumentOutOfRangeException: `password` length exceeds 256 characters

  • methodNeedsRehash
    public bool NeedsRehash(string hashedPassword)

    Determines whether the given stored password hash requires rehashing due to parameter updates or algorithm evolution.

    hashedPassword: string
    The stored hash string to evaluate

    Retorna: `true` if the hash should be regenerated with current parameters; otherwise, `false`.

    Migration promotion: Delegates directly to the primary hasher's `NeedsRehash` implementation. If the stored hash was produced by a different algorithm than the primary (e.g., the hash has an `$argon2id$` prefix but the primary hasher is `Pbkdf2PasswordHasher`), the primary hasher will not recognise the prefix and will return `true`. This means all non-primary-algorithm hashes always report `NeedsRehash = true`, intentionally promoting rehash to the current primary algorithm on the next successful authentication. If you need to check rehash eligibility for the algorithm that produced the hash, use `VerifyPassword` instead — `SuccessRehashNeeded` is returned whenever the matched hasher is not the primary or indicates its own cost parameters are outdated.

  • methodVerifyPassword
    public PasswordVerificationResult VerifyPassword(ReadOnlySpan<char> password, string hashedPassword)

    Verifies a plaintext password against a stored hashed password using constant-time evaluation.

    password: ReadOnlySpan<char>
    The candidate password character span to verify
    hashedPassword: string
    The stored hashed password string to evaluate

    Retorna: A `PasswordVerificationResult` indicating success, success with rehash required, or failure.

  • propertyAlgorithm
    public PasswordHashAlgorithm Algorithm { get; }

    Gets the primary password hashing algorithm implemented by this instance.

class

LegacyPbkdf2PasswordHasher

Ensamblado: EricksonLopez.Security
public sealed class LegacyPbkdf2PasswordHasher : IPasswordHasher
Implementa: IPasswordHasher

Provides a PBKDF2-HMAC-SHA512 password hasher that emits hashes using the `$legacy-pbkdf2$` modular crypt prefix (native) and can also verify hashes in the legacy `$argon2id$` format produced by earlier versions of this hasher (see ADR-024).

Notas:

Cryptographic Substrate: The underlying key derivation function is PBKDF2-HMAC-SHA512 (via `Rfc2898DeriveBytes.Pbkdf2`), not the Argon2id memory-hard algorithm described in RFC 9106. The actual iteration count applied to PBKDF2 is `iterations × 70,000` (default: `3 × 70,000 = 210,000`). The `m=` (memory) and `p=` (parallelism) cost parameters are stored as format metadata and participate in `NeedsRehash` comparison, but are not consumed by the derivation function. Format compatibility: New hashes produced by this hasher use the `$legacy-pbkdf2$` prefix. Hashes with the old `$argon2id$` prefix (produced by earlier versions) are verified transparently and flagged for rehash via `NeedsRehash`. Both formats are routed through `CompositePasswordHasher` alongside PBKDF2 hashes. Security posture: PBKDF2-HMAC-SHA512 at 210,000+ iterations meets OWASP and NIST SP 800-63B recommendations and provides GPU resistance via SHA-512's compute cost. It is not memory-hard; consider this when evaluating against hardware accelerated offline attacks.

Miembros (10)

  • constructorLegacyPbkdf2PasswordHasher
    public LegacyPbkdf2PasswordHasher(int memorySizeKb = 65536, int iterations = 3, int parallelism = 4, int saltSizeBytes = 16)

    Initializes a new instance of the `LegacyPbkdf2PasswordHasher` class.

    memorySizeKb: int
    Memory cost in kibibytes stored in the hash format header (e.g. `m=65536`). Participates in format-level rehash detection via `NeedsRehash` without being consumed by the underlying PBKDF2 derivation function.
    iterations: int
    Time-cost iteration multiplier where effective PBKDF2 iterations equal `iterations × 70,000`. Default is `3` (210,000 PBKDF2 rounds), stored as `t=` in the hash header.
    parallelism: int
    Degree of parallelism stored in the hash format header (e.g. `p=4`). Participates in format-level rehash detection via `NeedsRehash` without being consumed by the underlying PBKDF2 derivation function.
    saltSizeBytes: int
    The length of the generated cryptographic salt in bytes, defaulting to 16.

    Exceptions: ArgumentOutOfRangeException: Any parameter is outside its permitted range

  • methodHashPassword
    public string HashPassword(ReadOnlySpan<char> password)

    Computes a cryptographically salted and parameterized password hash for the specified password.

    password: ReadOnlySpan<char>
    The plaintext password character span. Must not exceed 256 characters.

    Retorna: A standardized, self-describing password hash string.

    Exceptions: ArgumentOutOfRangeException: `password` length exceeds 256 characters

  • methodNeedsRehash
    public bool NeedsRehash(string hashedPassword)

    Determines whether the given stored password hash requires rehashing due to parameter updates or algorithm evolution.

    hashedPassword: string
    The stored hash string to evaluate

    Retorna: `true` if the hash should be regenerated with current parameters; otherwise, `false`.

  • methodVerifyPassword
    public PasswordVerificationResult VerifyPassword(ReadOnlySpan<char> password, string hashedPassword)

    Verifies a plaintext password against a stored hashed password using constant-time evaluation.

    password: ReadOnlySpan<char>
    The candidate password character span to verify
    hashedPassword: string
    The stored hashed password string to evaluate

    Retorna: A `PasswordVerificationResult` indicating success, success with rehash required, or failure.

  • propertyAlgorithm
    public PasswordHashAlgorithm Algorithm { get; }

    Gets the primary password hashing algorithm implemented by this instance.

    SEC-005 fix: Returns `PasswordHashAlgorithm.Pbkdf2HmacSha512` — the actual cryptographic substrate is PBKDF2-HMAC-SHA512, not the memory-hard Argon2id algorithm described in RFC 9106. The hash format prefix (`$legacy-pbkdf2$` or legacy `$argon2id$`) is a format identifier separate from the cryptographic algorithm actually applied during key derivation. See ADR-024 and `SubstrateDescription` for more details.

  • propertyIsMemoryHard
    public static bool IsMemoryHard { get; }

    Gets a value indicating whether the underlying key derivation function is memory-hard.

    Evaluates to `false` per ADR-024 because the v1.x substrate is PBKDF2-HMAC-SHA512.

  • propertySubstrateDescription
    public static string SubstrateDescription { get; }

    Gets the cryptographic substrate name backing this hasher.

  • fieldDefault
    public static readonly LegacyPbkdf2PasswordHasher Default

    Gets the default singleton instance configured with 64 MB memory, 3 time-cost iterations (effective PBKDF2 iterations: 210,000), and 4 parallelism lanes.

  • fieldMaxAllowedTimeCost
    public const int MaxAllowedTimeCost

    Maximum time-cost multiplier accepted from a stored hash during verification. Effective PBKDF2 iterations = storedTimeCost × 70,000; a cap of 10 limits computation to 700,000 PBKDF2 iterations — preventing DoS (DOS-001 / SEC-002).

  • fieldMinAllowedTimeCost
    public const int MinAllowedTimeCost

    Minimum allowed time cost parameter (`t`) accepted by this hasher.

class

Pbkdf2PasswordHasher

Ensamblado: EricksonLopez.Security
public sealed class Pbkdf2PasswordHasher : IPasswordHasher
Implementa: IPasswordHasher

Provides a Password-Based Key Derivation Function 2 (PBKDF2) password hasher using HMAC-SHA512 per RFC 8018 and NIST SP 800-63B / OWASP recommendations. Formats hashes using the modular crypt format: `$pbkdf2-sha512$i=210000$s=<salt>$<hash>`.

Notas:

Architectural Tier (ADR-023): Belongs to the Tier 2 — Application Password Layer within the dual PBKDF2 architecture. It uses the modular crypt format `$pbkdf2-sha512$i={iterations}$s={salt}${hash}` with a default of 210,000 iterations (OWASP-recommended minimum for SHA-512). Format incompatibility warning: The hash format produced by this implementation (`$pbkdf2-sha512$` prefix) is not interoperable with the standalone `EricksonLopez.Security.Cryptography.Pbkdf2PasswordHasher`, which uses the `PBKDF2.V1$` prefix with 600,000 iterations and a different salt encoding. Mixing hashes from both tiers in the same storage table and routing them through the wrong hasher will cause all verifications to return `Failed`. See ADR-023 for the complete tier segregation rationale and migration guidance. Registration: When using `AddEricksonLopezSecurity()` or `AddPasswordSecurity()`, this hasher is registered as the primary hasher inside `CompositePasswordHasher`. New passwords are hashed with the `$pbkdf2-sha512$` format. Existing `$argon2id$` hashes are verified transparently and flagged for rehash on next successful login.

Miembros (8)

  • constructorPbkdf2PasswordHasher
    public Pbkdf2PasswordHasher(int iterations = DefaultIterations, int saltSizeBytes = DefaultSaltSizeBytes, int derivedKeySizeBytes = DefaultDerivedSizeBytes)

    Initializes a new instance of the `Pbkdf2PasswordHasher` class.

    iterations: int
    The number of PBKDF2 iterations (defaults to 210,000).
    saltSizeBytes: int
    The salt size in bytes (defaults to 16).
    derivedKeySizeBytes: int
    The derived key size in bytes (defaults to 32).

    Exceptions: ArgumentOutOfRangeException: `iterations` is less than 10,000 or greater than 600,000

  • methodHashPassword
    public string HashPassword(ReadOnlySpan<char> password)

    Computes a cryptographically salted and parameterized password hash for the specified password.

    password: ReadOnlySpan<char>
    The plaintext password character span. Must not exceed 256 characters.

    Retorna: A standardized, self-describing password hash string.

    Exceptions: ArgumentOutOfRangeException: `password` length exceeds 256 characters

  • methodNeedsRehash
    public bool NeedsRehash(string hashedPassword)

    Determines whether the given stored password hash requires rehashing due to parameter updates or algorithm evolution.

    hashedPassword: string
    The stored hash string to evaluate

    Retorna: `true` if the hash should be regenerated with current parameters; otherwise, `false`.

  • methodVerifyPassword
    public PasswordVerificationResult VerifyPassword(ReadOnlySpan<char> password, string hashedPassword)

    Verifies a plaintext password against a stored hashed password using constant-time evaluation.

    password: ReadOnlySpan<char>
    The candidate password character span to verify
    hashedPassword: string
    The stored hashed password string to evaluate

    Retorna: A `PasswordVerificationResult` indicating success, success with rehash required, or failure.

  • propertyAlgorithm
    public PasswordHashAlgorithm Algorithm { get; }

    Gets the primary password hashing algorithm implemented by this instance.

  • fieldDefault
    public static readonly Pbkdf2PasswordHasher Default

    Gets the default singleton instance configured with 210,000 iterations, 16-byte salt, and 32-byte derived key.

  • fieldDefaultIterations
    public const int DefaultIterations

    Gets the default recommended iterations for PBKDF2-HMAC-SHA512 (210,000 per OWASP guidance).

  • fieldMaxStoredIterations
    public const int MaxStoredIterations

    Maximum iteration count accepted from a stored hash string during verification (DoS prevention, FINDING-NEW-01).

EricksonLopez.Security.Pci#

1
class

PciDataGuard

Ensamblado: EricksonLopez.Security
public static class PciDataGuard

Provides zero-reflection PCI-DSS SAQ-A/A-EP cardholder data guards that detect, reject, and redact 13-to-19 digit Luhn-valid Primary Account Numbers (PAN), magnetic stripe Track 1/Track 2 data, and raw CVV/CVC values.

Miembros (6)

  • methodContainsLuhnPan
    public static bool ContainsLuhnPan(ReadOnlySpan<char> input)

    Determines whether `input` contains a 13-to-19 digit sequence (allowing single spaces or hyphens as separators) that passes the Luhn check.

    input: ReadOnlySpan<char>
    The character span to scan.

    Retorna: `true` if a Luhn-valid PAN sequence is detected; otherwise, `false`.

  • methodContainsTrackData
    public static bool ContainsTrackData(ReadOnlySpan<char> input)

    Determines whether `input` contains ISO/IEC 7813 magnetic stripe Track 1 (`%B...^`) or Track 2 (`;...=`) sentinels.

    input: ReadOnlySpan<char>
    The character span to scan.

    Retorna: `true` if magnetic track data is detected; otherwise, `false`.

  • methodRedactPanSequences
    public static string RedactPanSequences(string? input)

    Redacts any Luhn-valid 13-to-19 digit PAN sequences inside `input` to `[REDACTED-PAN]`.

    input: string?
    The text to scrub.

    Retorna: The scrubbed string, or the original string reference when no PAN is present.

  • methodValidateNoCardholderData
    public static Result ValidateNoCardholderData(ReadOnlySpan<char> input)

    Validates that `input` contains neither a Luhn-valid 13-19 digit PAN nor magnetic stripe Track 1/2 data.

    input: ReadOnlySpan<char>
    The text or metadata payload to inspect.

    Retorna: A successful `Result` if clean; otherwise, a validation error describing the PCI violation.

  • methodValidatePaymentToken
    public static Result ValidatePaymentToken(string? token, int maxLength = DefaultMaxTokenLength)

    Validates an opaque PSP hosted-fields token, rejecting null/empty tokens, control bytes, raw 3-4 digit CVVs, and raw PAN/track sequences.

    token: string?
    The candidate payment token.
    maxLength: int
    The maximum permitted token length. Defaults to 255.

    Retorna: A successful `Result` when the token is safe; otherwise, a validation error.

  • fieldDefaultMaxTokenLength
    public const int DefaultMaxTokenLength

    Default maximum length permitted for opaque payment gateway tokens.

EricksonLopez.Security.Pki#

5
class

CertificateChainValidator

Ensamblado: EricksonLopez.Security.Pki
public sealed class CertificateChainValidator : ICertificateChainValidator
Implementa: ICertificateChainValidator

Provides X.509 certificate chain validation and revocation verification using `X509Chain`.

Miembros (1)

  • methodValidateCertificate
    public Result<bool> ValidateCertificate(X509Certificate2 certificate, CertificateValidationOptions? options = null)

    Validates an X.509 certificate against the system or custom trust anchors and revocation rules.

    certificate: X509Certificate2
    The certificate to validate.
    options: CertificateValidationOptions?
    Optional validation options.

    Retorna: A successful result if the certificate and its chain are valid; otherwise, a security error.

enum

CertificateRevocationStatus

Ensamblado: EricksonLopez.Security.Pki
public enum CertificateRevocationStatus

Specifies the revocation status of an X.509 digital certificate.

Miembros (3)

  • fieldRevoked
    Revoked = 1

    Indicates that the certificate has been revoked by the issuing Certificate Authority.

  • fieldUnknown
    Unknown = 2

    Indicates that the certificate revocation status cannot be determined due to network or accessibility issues.

  • fieldValid
    Valid = 0

    Indicates that the certificate is verified as valid and not revoked.

class

CertificateValidationOptions

Ensamblado: EricksonLopez.Security.Pki
public sealed class CertificateValidationOptions

Specifies configuration options for X.509 certificate chain validation and revocation verification.

Miembros (9)

  • propertyCustomTrustAnchors
    public IList<X509Certificate2> CustomTrustAnchors { get; set; }

    Gets or sets a collection of custom trusted root CA certificates.

  • propertyDisableCertificateDownloads
    public bool DisableCertificateDownloads { get; set; }

    Gets or sets a value indicating whether network downloading of missing intermediate certificates via AIA is disabled. Default is `true` to prevent SSRF and network latency spikes.

  • propertyExpectedHostName
    public string? ExpectedHostName { get; set; }

    Gets or sets an optional expected host name (FQDN) to validate against the certificate's Subject Alternative Names (SAN) or Subject Common Name.

  • propertyMinimumEcdsaKeySize
    public int MinimumEcdsaKeySize { get; set; }

    Gets or sets the minimum allowed ECDSA key size in bits. Default is 256.

  • propertyMinimumRsaKeySize
    public int MinimumRsaKeySize { get; set; }

    Gets or sets the minimum allowed RSA key size in bits. Default is 2048.

  • propertyRequiredExtendedKeyUsageOid
    public string? RequiredExtendedKeyUsageOid { get; set; }

    Gets or sets an optional required Extended Key Usage (EKU) OID (e.g. "1.3.6.1.5.5.7.3.1" for Server Authentication).

  • propertyRevocationFlag
    public X509RevocationFlag RevocationFlag { get; set; }

    Gets or sets the revocation flag specifying whether to check revocation for the entire chain or end-entity only. Default is `X509RevocationFlag.EntireChain` (secure-by-default to verify all intermediate CAs).

  • propertyRevocationMode
    public X509RevocationMode RevocationMode { get; set; }

    Gets or sets the revocation checking mode. Default is `X509RevocationMode.Online` (secure-by-default).

  • propertyUrlRetrievalTimeout
    public TimeSpan UrlRetrievalTimeout { get; set; }

    Gets or sets the network timeout for certificate revocation and chain retrieval. Default is 5 seconds.

interface

ICertificateChainValidator

Ensamblado: EricksonLopez.Security.Pki
public interface ICertificateChainValidator

Defines certificate chain verification and trust anchor evaluation.

Miembros (1)

  • methodValidateCertificate
    Result<bool> ValidateCertificate(X509Certificate2 certificate, CertificateValidationOptions? options = null)

    Validates an X.509 certificate against the system or custom trust anchors and revocation rules.

    certificate: X509Certificate2
    The certificate to validate.
    options: CertificateValidationOptions?
    Optional validation options.

    Retorna: A successful result if the certificate and its chain are valid; otherwise, a security error.

class

SecurityPkiServiceCollectionExtensions

Ensamblado: EricksonLopez.Security.Pki
public static class SecurityPkiServiceCollectionExtensions

Provides extension methods for registering Public Key Infrastructure (PKI) certificate validation services into the service collection.

Miembros (1)

  • methodAddSecurityPki
    public static IServiceCollection AddSecurityPki(this IServiceCollection services)

    Registers the `ICertificateChainValidator` implementation into the service collection.

    services: this IServiceCollection
    The service collection to configure.

    Retorna: The same service collection instance for method chaining.

    Exceptions: ArgumentNullException: `services` is `null`

EricksonLopez.Security.Privacy.Hibp.Abstractions#

2
interface

IHaveIBeenPwnedClient

Ensamblado: EricksonLopez.Security.Privacy.Hibp
public interface IHaveIBeenPwnedClient

Defines a client contract for querying the Have I Been Pwned (HIBP) API using privacy-preserving k-Anonymity.

Miembros (2)

  • methodCheckPasswordAsync
    Task<Result<PwnedPasswordCheckResult>> CheckPasswordAsync(string password, CancellationToken cancellationToken = default)

    Determines whether a plaintext password has been exposed in data breaches without sending the full hash or plaintext over the network.

    password: string
    The plaintext password to check.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a result with the check outcome.

  • methodGetRangeAsync
    Task<Result<IReadOnlyList<PwnedPasswordEntry>>> GetRangeAsync(string hashPrefix, CancellationToken cancellationToken = default)

    Queries the HIBP range API with a 5-character SHA-1 hexadecimal prefix.

    hashPrefix: string
    The 5-character uppercase SHA-1 prefix.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a collection of matching hash suffixes and breach counts.

interface

IPasswordPwnedValidator

Ensamblado: EricksonLopez.Security.Privacy.Hibp
public interface IPasswordPwnedValidator

Defines a validator contract for enforcing that user passwords have not been compromised in publicly known data breaches.

Miembros (1)

  • methodValidateNotPwnedAsync
    Task<Result> ValidateNotPwnedAsync(string password, CancellationToken cancellationToken = default)

    Validates that the provided password has not been exposed in data breaches exceeding the configured threshold.

    password: string
    The plaintext password to validate.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a successful result if clean, or a validation failure describing the breach count.

EricksonLopez.Security.Privacy.Hibp.Clients#

1
class

HaveIBeenPwnedClient

Ensamblado: EricksonLopez.Security.Privacy.Hibp
public sealed class HaveIBeenPwnedClient : IHaveIBeenPwnedClient
Implementa: IHaveIBeenPwnedClient

Provides a Have I Been Pwned API client enforcing privacy-preserving k-Anonymity and anti-traffic analysis padding.

Miembros (3)

  • constructorHaveIBeenPwnedClient
    public HaveIBeenPwnedClient(HttpClient httpClient, IOptions<HibpOptions> options, ILogger<HaveIBeenPwnedClient>? logger = null)

    Initializes a new instance of the `HaveIBeenPwnedClient` class.

    httpClient: HttpClient
    The HTTP client for communicating with the Have I Been Pwned range API.
    options: IOptions<HibpOptions>
    The configured HIBP integration options accessor.
    logger: ILogger<HaveIBeenPwnedClient>?
    Optional logger instance for diagnostic events.

    Exceptions: ArgumentNullException: `httpClient` or `options` is `null`

  • methodCheckPasswordAsync
    public async Task<Result<PwnedPasswordCheckResult>> CheckPasswordAsync(string password, CancellationToken cancellationToken = default)

    Determines whether a plaintext password has been exposed in data breaches without sending the full hash or plaintext over the network.

    password: string
    The plaintext password to check.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a result with the check outcome.

  • methodGetRangeAsync
    public async Task<Result<IReadOnlyList<PwnedPasswordEntry>>> GetRangeAsync(string hashPrefix, CancellationToken cancellationToken = default)

    Queries the HIBP range API with a 5-character SHA-1 hexadecimal prefix.

    hashPrefix: string
    The 5-character uppercase SHA-1 prefix.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a collection of matching hash suffixes and breach counts.

EricksonLopez.Security.Privacy.Hibp.DependencyInjection#

1
class

HibpServiceCollectionExtensions

Ensamblado: EricksonLopez.Security.Privacy.Hibp
public static class HibpServiceCollectionExtensions

Provides extension methods for registering Have I Been Pwned privacy services in an `IServiceCollection`.

Miembros (1)

  • methodAddHaveIBeenPwned
    public static IServiceCollection AddHaveIBeenPwned(this IServiceCollection services, Action<HibpOptions>? configureOptions = null)

    Registers the Have I Been Pwned k-Anonymity client and password validator.

    services: this IServiceCollection
    The service collection to register services into.
    configureOptions: Action<HibpOptions>?
    An optional configuration delegate for HIBP options.

    Retorna: The configured `IServiceCollection` instance.

    Exceptions: ArgumentNullException: `services` is `null`

EricksonLopez.Security.Privacy.Hibp.Models#

3
class

HibpOptions

Ensamblado: EricksonLopez.Security.Privacy.Hibp
public sealed class HibpOptions

Specifies configuration options for the Have I Been Pwned (HIBP) API client and validator.

Miembros (5)

  • propertyAddPadding
    public bool AddPadding { get; set; }

    Gets or sets a value indicating whether to include the `Add-Padding: true` HTTP header to protect against side-channel traffic analysis.

  • propertyBaseUrl
    public string BaseUrl { get; set; }

    Gets or sets the base URL for the HIBP Pwned Passwords API.

  • propertyMaxAllowedBreachCount
    public long MaxAllowedBreachCount { get; set; }

    Gets or sets the maximum allowable breach count for password validation (0 requires password to be completely unbreached).

  • propertyTimeout
    public TimeSpan Timeout { get; set; }

    Gets or sets the HTTP request timeout.

  • propertyUserAgent
    public string UserAgent { get; set; }

    Gets or sets the User-Agent header string (mandatory per HIBP API policy).

record

PwnedPasswordCheckResult

Ensamblado: EricksonLopez.Security.Privacy.Hibp
public sealed record PwnedPasswordCheckResult

Represents the result of querying a password against the HIBP breached database.

Miembros (4)

  • constructorPwnedPasswordCheckResult
    public PwnedPasswordCheckResult(string hashPrefix, long breachCount)

    Initializes a new instance of the `PwnedPasswordCheckResult` record with the specified hash prefix and breach count.

    hashPrefix: string
    Five-character SHA-1 prefix representing the k-Anonymity range lookup.
    breachCount: long
    Total number of observed occurrences in breached databases.

    Exceptions: ArgumentException: `hashPrefix` is `null`, empty, or whitespace

  • propertyBreachCount
    public long BreachCount { get; init; }

    Gets the number of times this password appeared in known breaches (0 if clean).

  • propertyHashPrefix
    public string HashPrefix { get; init; }

    Gets the 5-character SHA-1 prefix representing the k-Anonymity range lookup.

  • propertyIsPwned
    public bool IsPwned { get; }

    Gets a value indicating whether the password was found in known data breaches.

record

PwnedPasswordEntry

Ensamblado: EricksonLopez.Security.Privacy.Hibp
public sealed record PwnedPasswordEntry

Represents an entry returned from the HIBP range search API containing a SHA-1 hash suffix and breach frequency count.

Miembros (3)

  • constructorPwnedPasswordEntry
    public PwnedPasswordEntry(string suffix, long breachCount)

    Initializes a new instance of the `PwnedPasswordEntry` record with the specified hash suffix and breach frequency count.

    suffix: string
    The 35-character uppercase hexadecimal SHA-1 hash suffix.
    breachCount: long
    The number of times this password appeared in known data breaches.

    Exceptions: ArgumentException: `suffix` is `null`, empty, or whitespace

  • propertyBreachCount
    public long BreachCount { get; init; }

    Gets the number of times this password appeared in known data breaches.

  • propertySuffix
    public string Suffix { get; init; }

    Gets the 35-character uppercase hexadecimal SHA-1 hash suffix.

EricksonLopez.Security.Privacy.Hibp.Validators#

1
class

PasswordPwnedValidator

Ensamblado: EricksonLopez.Security.Privacy.Hibp
public sealed class PasswordPwnedValidator : IPasswordPwnedValidator
Implementa: IPasswordPwnedValidator

Validates that passwords have not appeared in known public data breaches.

Miembros (2)

  • constructorPasswordPwnedValidator
    public PasswordPwnedValidator(IHaveIBeenPwnedClient client, IOptions<HibpOptions> options, ILogger<PasswordPwnedValidator>? logger = null)

    Initializes a new instance of the `PasswordPwnedValidator` class.

    client: IHaveIBeenPwnedClient
    The Have I Been Pwned API client for performing range queries.
    options: IOptions<HibpOptions>
    The configured HIBP integration options accessor.
    logger: ILogger<PasswordPwnedValidator>?
    Optional logger instance for diagnostic events.

    Exceptions: ArgumentNullException: `client` or `options` is `null`

  • methodValidateNotPwnedAsync
    public async Task<Result> ValidateNotPwnedAsync(string password, CancellationToken cancellationToken = default)

    Validates that the provided password has not been exposed in data breaches exceeding the configured threshold.

    password: string
    The plaintext password to validate.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a successful result if clean, or a validation failure describing the breach count.

EricksonLopez.Security.Randomness#

3
class

ConstantTimeComparer

Ensamblado: EricksonLopez.Security
public sealed class ConstantTimeComparer : IConstantTimeComparer
Implementa: IConstantTimeComparer

Provides side-channel resistant constant-time comparison primitives wrapping `CryptographicOperations.FixedTimeEquals`.

Miembros (7)

  • constructorConstantTimeComparer
    public ConstantTimeComparer()

    Initializes a new instance of the `ConstantTimeComparer` class.

  • methodEquals
    public static bool Equals(string? left, string? right)

    Compares two strings in constant time, resistant to value-based timing side channels.

    left: string?
    The left string.
    right: string?
    The right string.

    Retorna: `true` if strings are identical in constant time; otherwise, `false`.

    Note (SC-NULL-001): When exactly one argument is `null`, this method executes a dummy constant-time comparison before returning `false` to prevent a timing side-channel that would otherwise reveal whether either string is `null` ahead of the constant-time comparison. This protects callers that pass hashes or tokens where a missing/null value could have a distinct timing signature.

  • methodFixedTimeEquals
    public bool FixedTimeEquals(ReadOnlySpan<byte> left, ReadOnlySpan<byte> right)

    Compares two byte spans for equality in execution time independent of data values, preventing side-channel timing attacks.

    left: ReadOnlySpan<byte>
    The left byte span.
    right: ReadOnlySpan<byte>
    The right byte span.

    Retorna: `true` if byte contents are identical and equal length; otherwise, `false`.

  • methodFixedTimeEquals
    public bool FixedTimeEquals(ReadOnlySpan<char> left, ReadOnlySpan<char> right)

    Compares two byte spans for equality in execution time independent of data values, preventing side-channel timing attacks.

    left: ReadOnlySpan<char>
    The left byte span.
    right: ReadOnlySpan<char>
    The right byte span.

    Retorna: `true` if byte contents are identical and equal length; otherwise, `false`.

    Encoding Note (CTC-04): This overload compares the UTF-16 LE byte representation of the two character spans, as stored in memory by the .NET runtime. This is correct and safe for all comparisons of `string`-derived spans (e.g., `token.AsSpan()`, `header.AsSpan()`). Do not use this overload to compare characters reconstructed from different source encodings (e.g., a `char[]` decoded from UTF-8 bytes vs a native .NET string). The UTF-16 LE byte layout must be identical for both operands, which is guaranteed when both originate from .NET `string` objects.

  • methodFixedTimeEqualsSecure
    public bool FixedTimeEqualsSecure(ReadOnlySpan<byte> left, ReadOnlySpan<byte> right)

    Compares two character spans for equality in constant time, eliminating length-leakage side channels by hashing both inputs with a cryptographic digest before constant-time evaluation.

    left: ReadOnlySpan<byte>
    The left character span.
    right: ReadOnlySpan<byte>
    The right character span.

    Retorna: `true` if both spans are identical; otherwise, `false`.

  • methodFixedTimeEqualsSecure
    public bool FixedTimeEqualsSecure(ReadOnlySpan<char> left, ReadOnlySpan<char> right)

    Compares two character spans for equality in constant time, eliminating length-leakage side channels by hashing both inputs with a cryptographic digest before constant-time evaluation.

    left: ReadOnlySpan<char>
    The left character span.
    right: ReadOnlySpan<char>
    The right character span.

    Retorna: `true` if both spans are identical; otherwise, `false`.

  • fieldShared
    public static readonly ConstantTimeComparer Shared

    Gets the shared singleton instance of `ConstantTimeComparer`.

class

CryptographicRandom

Ensamblado: EricksonLopez.Security
public sealed class CryptographicRandom : ICryptographicRandomNumberGenerator
Implementa: ICryptographicRandomNumberGenerator

Provides a thread-safe implementation of `ICryptographicRandomNumberGenerator` utilizing the underlying operating system Cryptographically Secure Pseudo-Random Number Generator (CSPRNG).

Miembros (8)

  • constructorCryptographicRandom
    public CryptographicRandom()

    Initializes a new instance of the `CryptographicRandom` class.

  • methodFill
    public void Fill(Span<byte> destination)

    Fills the destination byte span with cryptographically strong random bytes.

    destination: Span<byte>
    The destination span.
  • methodGetBytes
    public byte[] GetBytes(int count)

    Allocates and fills a byte array with cryptographically strong random bytes.

    count: int
    The number of bytes to generate.

    Retorna: A byte array containing cryptographically strong random bytes.

  • methodGetHexString
    public string GetHexString(int byteLength = 32)

    Generates a cryptographically random lowercase hex string with the specified byte entropy.

    byteLength: int
    The entropy byte count.

    Retorna: A hex-encoded random string.

    Exceptions: ArgumentOutOfRangeException: `byteLength` is less than or equal to zero

  • methodGetInt32
    public int GetInt32(int fromInclusive, int toExclusive)

    Generates a cryptographically strong random integer within the specified range.

    fromInclusive: int
    The inclusive lower bound.
    toExclusive: int
    The exclusive upper bound.

    Retorna: A cryptographically strong random integer within the specified range.

  • methodGetUrlSafeString
    public string GetUrlSafeString(int byteLength = 32)

    Generates a cryptographically random URL-safe base64 string with the specified byte entropy.

    byteLength: int
    The entropy byte count.

    Retorna: A URL-safe random string.

    Memory Note (RNG-04): The returned `string` is a managed heap allocation. .NET strings are immutable and cannot be explicitly zeroed — the token material may remain in memory until the next garbage collection cycle. For callers where minimizing the secret exposure window is critical (e.g., session tokens, API secrets), prefer `TryGetUrlSafeString(Span<char>, int, out int)`, which writes directly into a caller-controlled `Span<T>` that can be zeroed after use. Exceptions: ArgumentOutOfRangeException: `byteLength` is less than or equal to zero

  • methodTryGetUrlSafeString
    public bool TryGetUrlSafeString(Span<char> destination, int byteLength, out int charsWritten)

    Attempts to generate a cryptographically random URL-safe base64 string into the specified destination span.

    destination: Span<char>
    The destination character span to receive the encoded string.
    byteLength: int
    The number of random entropy bytes to generate. Must be greater than zero.
    charsWritten: out int
    When this method returns, contains the number of characters written to `destination`.

    Retorna: `true` if the characters were successfully written; otherwise, `false`.

    Exceptions: ArgumentOutOfRangeException: `byteLength` is less than or equal to zero

  • fieldShared
    public static readonly CryptographicRandom Shared

    Gets the shared singleton instance of `CryptographicRandom`.

struct

TimingSafeString

Ensamblado: EricksonLopez.Security
public readonly struct TimingSafeString : IEquatable<TimingSafeString>
Implementa: IEquatable<TimingSafeString>

Represents a readonly wrapper for strings that uses constant-time comparison in `Equals(TimingSafeString)` and `operator ==` to prevent timing side-channel attacks on credentials, tokens, and HMACs.

Miembros (11)

  • constructorTimingSafeString
    public TimingSafeString(string? value)

    Initializes a new instance of the `TimingSafeString` struct.

    value: string?
    The string value.
  • methodAsSpan
    public ReadOnlySpan<char> AsSpan()

    Returns a read-only character span representing the underlying characters.

    Retorna: A read-only span representing the underlying characters.

    Lifetime Note (TSS-03): The returned `ReadOnlySpan<T>` is directly bound to the underlying `string` field of this `TimingSafeString` instance. The span must not be stored beyond the lifetime of this instance \u2014 it will become invalid if the instance is garbage collected. In practice, consume the span immediately within the same call scope and do not pass it to asynchronous continuations, background threads, or stored delegates.

  • methodEquals
    public override bool Equals(object? obj)

    Inherits documentation from base type or interface.

    obj: object?
  • methodEquals
    public bool Equals(TimingSafeString other)

    Inherits documentation from base type or interface.

    other: TimingSafeString
  • methodGetHashCode
    public override int GetHashCode()

    Inherits documentation from base type or interface.

    Security Warning (SC-002): This method returns a standard, non-constant-time hash code derived from the underlying string. Using `TimingSafeString` as a key in a `Generic.Dictionary<TKey, TValue>` or `Generic.HashSet<T>` will NOT preserve constant-time properties because dictionary bucket lookups use this hash code with ordinary timing. Use `Equals(TimingSafeString)` or `operator ==(TimingSafeString, TimingSafeString)` for constant-time comparisons. This method is hidden in IDE auto-complete to discourage misuse.

  • methodToString
    public override string ToString()

    Inherits documentation from base type or interface.

  • methodimplicit operator TimingSafeString
    public static implicit operator TimingSafeString(string? value)

    Converts a string to a `TimingSafeString` instance.

    value: string?
    The string value to wrap.

    Retorna: A new `TimingSafeString` wrapping `value`.

  • methodoperator !=
    public static bool operator !=(TimingSafeString left, TimingSafeString right)

    Determines whether two `TimingSafeString` instances represent different values using constant-time comparison.

    left: TimingSafeString
    The first instance to compare.
    right: TimingSafeString
    The second instance to compare.

    Retorna: `true` if instances represent different values; otherwise, `false`.

  • methodoperator ==
    public static bool operator ==(TimingSafeString left, TimingSafeString right)

    Determines whether two `TimingSafeString` instances represent the same value using constant-time comparison.

    left: TimingSafeString
    The first instance to compare.
    right: TimingSafeString
    The second instance to compare.

    Retorna: `true` if both instances represent the same value; otherwise, `false`.

  • propertyIsEmpty
    public bool IsEmpty { get; }

    Gets a value indicating whether this instance holds an empty string.

  • propertyLength
    public int Length { get; }

    Gets the length of the string in characters.

EricksonLopez.Security.Saml2.Abstractions#

6
interface

ISaml2AssertionDecryptor

Ensamblado: EricksonLopez.Security.Saml2
public interface ISaml2AssertionDecryptor

Defines the contract for decrypting SAML 2.0 `<saml:EncryptedAssertion>` XML payloads.

Miembros (1)

  • methodDecryptAssertion
    Result<XmlElement> DecryptAssertion(XmlElement encryptedAssertionElement, X509Certificate2 decryptionCertificate)

    Decrypts an encrypted assertion element using the Service Provider's private key.

    encryptedAssertionElement: XmlElement
    The `<saml:EncryptedAssertion>` XML element.
    decryptionCertificate: X509Certificate2
    The certificate containing the SP private key.

    Retorna: A result containing the decrypted `<saml:Assertion>` XML element on success.

interface

ISaml2ClaimsMapper

Ensamblado: EricksonLopez.Security.Saml2
public interface ISaml2ClaimsMapper

Defines the contract for transforming validated SAML 2.0 assertions and attributes into .NET `ClaimsPrincipal` objects.

Miembros (1)

  • methodMapToPrincipal
    ClaimsPrincipal MapToPrincipal(Saml2Assertion assertion, Saml2Options options)

    Maps a SAML 2.0 assertion into a strongly-typed `ClaimsPrincipal`.

    assertion: Saml2Assertion
    The validated SAML 2.0 assertion.
    options: Saml2Options
    The SAML 2.0 options.

    Retorna: A new `ClaimsPrincipal` populated with standard claims.

interface

ISaml2ReplayCache

Ensamblado: EricksonLopez.Security.Saml2
public interface ISaml2ReplayCache

Defines a cache for preventing SAML 2.0 assertion replay attacks across HTTP requests.

Miembros (2)

  • methodContainsAsync
    Task<bool> ContainsAsync(string assertionId, CancellationToken cancellationToken = default)

    Checks whether an assertion ID is currently present in the cache and unexpired.

    assertionId: string
    The unique ID of the SAML assertion.
    cancellationToken: CancellationToken
    A token to cancel the operation.

    Retorna: `true` if the assertion ID exists in the cache; otherwise `false`.

  • methodTryAddAsync
    Task<bool> TryAddAsync(string assertionId, DateTimeOffset expiration, CancellationToken cancellationToken = default)

    Attempts to add an assertion ID to the cache with an expiration timestamp.

    assertionId: string
    The unique ID of the SAML assertion.
    expiration: DateTimeOffset
    The UTC timestamp when the assertion expires.
    cancellationToken: CancellationToken
    A token to cancel the operation.

    Retorna: `true` if the assertion ID was newly added; `false` if it was already processed (replay detected).

interface

ISaml2Service

Ensamblado: EricksonLopez.Security.Saml2
public interface ISaml2Service

Defines a service that orchestrates SAML 2.0 Web Browser Single Sign-On and Single Logout operations.

Miembros (7)

  • methodCreateAuthnRequest
    Saml2AuthnRequest CreateAuthnRequest(string? relayState = null)

    Generates a signed or unsigned `Saml2AuthnRequest` XML message to initiate SP-initiated SSO.

    relayState: string?
    The optional opaque RelayState string.

    Retorna: A new `Saml2AuthnRequest` model.

  • methodCreateLogoutRequest
    Saml2LogoutRequest CreateLogoutRequest(Saml2NameId nameId, string? sessionIndex = null, string? relayState = null)

    Creates a `<samlp:LogoutRequest>` XML message to initiate SP-initiated Single Logout.

    nameId: Saml2NameId
    The NameID of the principal whose session should be terminated.
    sessionIndex: string?
    The optional SessionIndex from the original assertion's AuthnStatement.
    relayState: string?
    The optional opaque RelayState string.

    Retorna: A new `Saml2LogoutRequest` model.

  • methodCreateLogoutResponse
    Saml2LogoutResponse CreateLogoutResponse(string inResponseTo, string destination, bool success = true)

    Creates a `<samlp:LogoutResponse>` XML message in response to an IdP-initiated `<samlp:LogoutRequest>` (for SP-side SLO response).

    inResponseTo: string
    The ID of the incoming IdP LogoutRequest.
    destination: string
    The IdP's SLO response URL.
    success: bool
    A value indicating whether the SP successfully terminated the local session.

    Retorna: A `Saml2LogoutResponse` model containing the SP's SLO response XML.

  • methodGenerateSpMetadata
    string GenerateSpMetadata()

    Generates an SP Metadata XML document that describes the Service Provider endpoints, capabilities, and certificates to federate with Identity Providers.

    Retorna: A well-formed `<md:EntityDescriptor>` XML string compliant with the SAML 2.0 Metadata Specification (saml-metadata-2.0-os).

  • methodProcessIdpInitiatedResponseAsync
    Task<Result<Saml2AuthenticationResult>> ProcessIdpInitiatedResponseAsync(string samlResponseXml, CancellationToken cancellationToken = default)

    Processes an IdP-initiated SAML 2.0 Response (unsolicited response without `InResponseTo`).

    samlResponseXml: string
    The raw XML or Base64-encoded SAML Response string from the IdP.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a result containing the authenticated principal and assertion on success.

    Security note: IdP-initiated SSO is inherently less secure than SP-initiated SSO because there is no request correlation. Enforces assertion ID replay protection to prevent assertion reuse attacks. `Saml2Options.AllowIdpInitiatedSso` must be set to `true` to enable this flow.

  • methodProcessLogoutResponseAsync
    Task<Result<Saml2LogoutResponse>> ProcessLogoutResponseAsync(string samlLogoutResponseXml, string expectedInResponseTo, CancellationToken cancellationToken = default)

    Validates an incoming `<samlp:LogoutResponse>` from the Identity Provider. Verifies signature, status code, and `InResponseTo` correlation.

    samlLogoutResponseXml: string
    The raw XML or Base64-encoded LogoutResponse string.
    expectedInResponseTo: string
    The ID of the `Saml2LogoutRequest` this is a response to.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a result containing the parsed `Saml2LogoutResponse` on success.

  • methodProcessSpInitiatedResponseAsync
    Task<Result<Saml2AuthenticationResult>> ProcessSpInitiatedResponseAsync(string samlResponseXml, Saml2RequestId expectedInResponseTo, CancellationToken cancellationToken = default)

    Processes an SP-initiated SAML 2.0 Response with strongly typed expected request ID correlation.

    samlResponseXml: string
    The raw XML or Base64-encoded SAML Response string.
    expectedInResponseTo: Saml2RequestId
    The strongly typed expected request ID.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A result containing the authenticated principal and assertion on success.

interface

ISaml2SignatureValidator

Ensamblado: EricksonLopez.Security.Saml2
public interface ISaml2SignatureValidator

Defines the contract for validating XMLDSig digital signatures on SAML 2.0 messages and assertions.

Miembros (2)

  • methodSignElement
    Result SignElement(XmlElement element, X509Certificate2 certificate)

    Signs an XML element using the provided certificate and appends the XMLDSig signature block.

    element: XmlElement
    The target XML element.
    certificate: X509Certificate2
    The signing certificate with private key.

    Retorna: A result indicating whether the signing operation succeeded.

  • methodVerifySignature
    Result VerifySignature(XmlElement element, X509Certificate2 certificate)

    Verifies the digital signature on a specific XML element against the provided certificate.

    element: XmlElement
    The XML element containing or targeted by the XMLDSig signature.
    certificate: X509Certificate2
    The trusted certificate.

    Retorna: A result indicating whether the signature is cryptographically valid.

interface

ISaml2XswValidator

Ensamblado: EricksonLopez.Security.Saml2
public interface ISaml2XswValidator

Defines the defense contract against XML Signature Wrapping (XSW) vulnerabilities (XSW1 to XSW8).

Miembros (1)

  • methodValidateAndExtractAssertion
    Result<XmlElement> ValidateAndExtractAssertion(XmlDocument document)

    Validates the XML document structure to ensure the verified signed element matches the exact element consumed by the business logic, rejecting any malicious signature wrapping or element injection.

    document: XmlDocument
    The XML document containing the SAML response.

    Retorna: A result containing the validated canonical assertion XML element on success.

EricksonLopez.Security.Saml2.Claims#

1
class

Saml2ClaimsMapper

Ensamblado: EricksonLopez.Security.Saml2
public sealed class Saml2ClaimsMapper : ISaml2ClaimsMapper
Implementa: ISaml2ClaimsMapper

Maps SAML 2.0 assertion attributes and NameID into standard .NET `ClaimsPrincipal` instances.

Miembros (1)

  • methodMapToPrincipal
    public ClaimsPrincipal MapToPrincipal(Saml2Assertion assertion, Saml2Options options)

    Maps a SAML 2.0 assertion into a strongly-typed `ClaimsPrincipal`.

    assertion: Saml2Assertion
    The validated SAML 2.0 assertion.
    options: Saml2Options
    The SAML 2.0 options.

    Retorna: A new `ClaimsPrincipal` populated with standard claims.

EricksonLopez.Security.Saml2.Cryptography#

2
class

Saml2AssertionDecryptor

Ensamblado: EricksonLopez.Security.Saml2
public sealed class Saml2AssertionDecryptor : ISaml2AssertionDecryptor
Implementa: ISaml2AssertionDecryptor

Decrypts SAML 2.0 `<saml:EncryptedAssertion>` structures.

Miembros (1)

  • methodDecryptAssertion
    public Result<XmlElement> DecryptAssertion(XmlElement encryptedAssertionElement, X509Certificate2 decryptionCertificate)

    Decrypts an encrypted assertion element using the Service Provider's private key.

    encryptedAssertionElement: XmlElement
    The `<saml:EncryptedAssertion>` XML element.
    decryptionCertificate: X509Certificate2
    The certificate containing the SP private key.

    Retorna: A result containing the decrypted `<saml:Assertion>` XML element on success.

class

Saml2SignatureValidator

Ensamblado: EricksonLopez.Security.Saml2
public sealed class Saml2SignatureValidator : ISaml2SignatureValidator
Implementa: ISaml2SignatureValidator

Validates and signs SAML 2.0 XML messages using XMLDSig standards.

Miembros (2)

  • methodSignElement
    public Result SignElement(XmlElement element, X509Certificate2 certificate)

    Signs an XML element using the provided certificate and appends the XMLDSig signature block.

    element: XmlElement
    The target XML element.
    certificate: X509Certificate2
    The signing certificate with private key.

    Retorna: A result indicating whether the signing operation succeeded.

  • methodVerifySignature
    public Result VerifySignature(XmlElement element, X509Certificate2 certificate)

    Verifies the digital signature on a specific XML element against the provided certificate.

    element: XmlElement
    The XML element containing or targeted by the XMLDSig signature.
    certificate: X509Certificate2
    The trusted certificate.

    Retorna: A result indicating whether the signature is cryptographically valid.

EricksonLopez.Security.Saml2.DependencyInjection#

1
class

Saml2ServiceCollectionExtensions

Ensamblado: EricksonLopez.Security.Saml2
public static class Saml2ServiceCollectionExtensions

Provides extension methods for registering SAML 2.0 Service Provider components in dependency injection.

Miembros (1)

  • methodAddSaml2Security
    public static IServiceCollection AddSaml2Security(this IServiceCollection services, Action<Saml2Options>? configureOptions = null)

    Registers SAML 2.0 Service Provider services with XSW defense and XMLDSig verification.

    services: this IServiceCollection
    The service collection.
    configureOptions: Action<Saml2Options>?
    An action to configure `Saml2Options`.

    Retorna: The `IServiceCollection` instance for chaining.

    Exceptions: ArgumentNullException: `services` is `null`

EricksonLopez.Security.Saml2.Enums#

4
enum

Saml2Binding

Ensamblado: EricksonLopez.Security.Saml2
public enum Saml2Binding

Defines SAML 2.0 protocol binding profiles.

Miembros (4)

  • fieldHttpArtifact
    HttpArtifact = 3

    Specifies the HTTP Artifact binding (`urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact`).

  • fieldHttpPost
    HttpPost = 1

    Specifies the HTTP POST binding (`urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST`).

  • fieldHttpRedirect
    HttpRedirect = 2

    Specifies the HTTP Redirect binding (`urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect`).

  • fieldSoap
    Soap = 4

    Specifies the SOAP binding (`urn:oasis:names:tc:SAML:2.0:bindings:SOAP`).

enum

Saml2NameIdFormat

Ensamblado: EricksonLopez.Security.Saml2
public enum Saml2NameIdFormat

Defines standard SAML 2.0 NameID format identifiers.

Miembros (5)

  • fieldEmailAddress
    EmailAddress = 1

    Specifies the email address NameID format (`urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress`).

  • fieldPersistent
    Persistent = 2

    Specifies the persistent pseudorandom NameID format (`urn:oasis:names:tc:SAML:2.0:nameid-format:persistent`).

  • fieldTransient
    Transient = 3

    Specifies the transient session-only NameID format (`urn:oasis:names:tc:SAML:2.0:nameid-format:transient`).

  • fieldUnspecified
    Unspecified = 0

    Specifies the unspecified NameID format (`urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified`).

  • fieldX509SubjectName
    X509SubjectName = 4

    Specifies the X.509 Subject Name format (`urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName`).

enum

Saml2SignatureLocation

Ensamblado: EricksonLopez.Security.Saml2
public enum Saml2SignatureLocation

Specifies the location of an XML digital signature within a SAML 2.0 message.

Miembros (3)

  • fieldAssertion
    Assertion = 2

    Specifies that the signature is placed inside individual `<saml:Assertion>` elements.

  • fieldBoth
    Both = 3

    Specifies that both the Response and the Assertion elements are digitally signed.

  • fieldResponse
    Response = 1

    Specifies that the signature is placed at the top-level `<samlp:Response>` element.

enum

Saml2StatusCode

Ensamblado: EricksonLopez.Security.Saml2
public enum Saml2StatusCode

Defines top-level SAML 2.0 response status codes.

Miembros (5)

  • fieldAuthnFailed
    AuthnFailed = 5

    Specifies that authentication failed at the Identity Provider (`urn:oasis:names:tc:SAML:2.0:status:AuthnFailed`).

  • fieldRequester
    Requester = 2

    Specifies that the request could not be fulfilled due to requester error (`urn:oasis:names:tc:SAML:2.0:status:Requester`).

  • fieldResponder
    Responder = 3

    Specifies that the request could not be fulfilled due to responder error (`urn:oasis:names:tc:SAML:2.0:status:Responder`).

  • fieldSuccess
    Success = 1

    Specifies that the request succeeded (`urn:oasis:names:tc:SAML:2.0:status:Success`).

  • fieldVersionMismatch
    VersionMismatch = 4

    Specifies that the responder does not support the request version (`urn:oasis:names:tc:SAML:2.0:status:VersionMismatch`).

EricksonLopez.Security.Saml2.Models#

15
record

Saml2Assertion

Ensamblado: EricksonLopez.Security.Saml2
public sealed record Saml2Assertion

Represents a validated, unencrypted SAML 2.0 Assertion.

Miembros (9)

  • constructorSaml2Assertion
    public Saml2Assertion(string id, DateTimeOffset issueInstant, string issuer, Saml2Subject subject, string rawXml, Saml2Conditions? conditions = null, Saml2AuthnStatement? authnStatement = null, IReadOnlyList<Saml2Attribute>? attributes = null)

    Initializes a new instance of the `Saml2Assertion` record with the specified assertion data.

    id: string
    The unique identifier of the assertion.
    issueInstant: DateTimeOffset
    The timestamp when the assertion was issued.
    issuer: string
    The Entity ID of the issuing Identity Provider.
    subject: Saml2Subject
    The authenticated security principal subject.
    rawXml: string
    The raw XML string representation of the assertion.
    conditions: Saml2Conditions?
    The optional validity conditions and audience restrictions.
    authnStatement: Saml2AuthnStatement?
    The optional authentication statement details.
    attributes: IReadOnlyList<Saml2Attribute>?
    The optional collection of user attributes.

    Exceptions: ArgumentNullException: `subject` is `null`; ArgumentException: `id`, `issuer`, or `rawXml` is `null`, empty, or whitespace

  • propertyAttributes
    public IReadOnlyList<Saml2Attribute> Attributes { get; init; }

    Gets the collection of user attributes.

  • propertyAuthnStatement
    public Saml2AuthnStatement? AuthnStatement { get; init; }

    Gets the authentication statement details.

  • propertyConditions
    public Saml2Conditions? Conditions { get; init; }

    Gets the validity conditions and audience restrictions.

  • propertyId
    public string Id { get; init; }

    Gets the unique ID of the assertion.

  • propertyIssueInstant
    public DateTimeOffset IssueInstant { get; init; }

    Gets the issue instant of the assertion.

  • propertyIssuer
    public string Issuer { get; init; }

    Gets the Entity ID of the issuing Identity Provider.

  • propertyRawXml
    public string RawXml { get; init; }

    Gets the raw XML string of the assertion.

  • propertySubject
    public Saml2Subject Subject { get; init; }

    Gets the authenticated Subject.

record

Saml2Attribute

Ensamblado: EricksonLopez.Security.Saml2
public sealed record Saml2Attribute

Represents a SAML 2.0 user attribute emitted by the Identity Provider.

Miembros (5)

  • constructorSaml2Attribute
    public Saml2Attribute(string name, IReadOnlyList<string> values, string? friendlyName = null, string? nameFormat = null)

    Initializes a new instance of the `Saml2Attribute` record with the specified attribute details.

    name: string
    The attribute name URI or friendly identifier.
    values: IReadOnlyList<string>
    The list of attribute string values.
    friendlyName: string?
    The optional human-readable attribute friendly name.
    nameFormat: string?
    The optional URI classifying the attribute name format.

    Exceptions: ArgumentException: `name` is `null`, empty, or whitespace

  • propertyFriendlyName
    public string? FriendlyName { get; init; }

    Gets the optional friendly name of the attribute.

  • propertyName
    public string Name { get; init; }

    Gets the attribute name (URI or friendly string).

  • propertyNameFormat
    public string? NameFormat { get; init; }

    Gets the attribute name format URI.

  • propertyValues
    public IReadOnlyList<string> Values { get; init; }

    Gets the list of string values for the attribute.

record

Saml2AuthenticationResult

Ensamblado: EricksonLopez.Security.Saml2
public sealed record Saml2AuthenticationResult

Represents the validated output of a SAML 2.0 authentication response ceremony.

Miembros (6)

  • constructorSaml2AuthenticationResult
    public Saml2AuthenticationResult(ClaimsPrincipal principal, Saml2Assertion assertion)

    Initializes a new instance of the `Saml2AuthenticationResult` record with the validated principal and assertion.

    principal: ClaimsPrincipal
    The authenticated claims principal constructed from the assertion.
    assertion: Saml2Assertion
    The validated SAML 2.0 assertion.

    Exceptions: ArgumentNullException: `principal` or `assertion` is `null`

  • propertyAssertion
    public Saml2Assertion Assertion { get; init; }

    Gets the validated SAML 2.0 assertion.

  • propertyIssuer
    public string Issuer { get; }

    Gets the Identity Provider Entity ID.

  • propertyNameId
    public string NameId { get; }

    Gets the primary NameID value.

  • propertyPrincipal
    public ClaimsPrincipal Principal { get; init; }

    Gets the principal identity constructed from the SAML assertion and attributes.

  • propertySessionIndex
    public string? SessionIndex { get; }

    Gets the optional session index for single logout (SLO).

record

Saml2AuthnRequest

Ensamblado: EricksonLopez.Security.Saml2
public sealed record Saml2AuthnRequest

Represents a SAML 2.0 AuthnRequest message generated by the Service Provider to initiate SSO.

Miembros (12)

  • constructorSaml2AuthnRequest
    public Saml2AuthnRequest(string id, string issuer, DateTimeOffset issueInstant, string destination, string assertionConsumerServiceUrl, string rawXml, Saml2Binding protocolBinding = Saml2Binding.HttpPost, Saml2NameIdFormat nameIdFormat = Saml2NameIdFormat.Unspecified, bool forceAuthn = false, bool isPassive = false, string? relayState = null)

    Initializes a new instance of the `Saml2AuthnRequest` record with the specified parameters.

    id: string
    The unique request message identifier.
    issuer: string
    The Entity ID of the Service Provider issuer.
    issueInstant: DateTimeOffset
    The timestamp when the request was generated.
    destination: string
    The destination SSO endpoint URI at the Identity Provider.
    assertionConsumerServiceUrl: string
    The Assertion Consumer Service (ACS) endpoint URL where the response will be sent.
    rawXml: string
    The raw XML string representation of the request.
    protocolBinding: Saml2Binding
    The protocol binding for receiving the response.
    nameIdFormat: Saml2NameIdFormat
    The requested NameID format policy.
    forceAuthn: bool
    A value indicating whether the IdP must forcibly re-authenticate the user.
    isPassive: bool
    A value indicating whether authentication must proceed without user interaction.
    relayState: string?
    The optional state string preserved across SSO redirects.

    Exceptions: ArgumentException: `id`, `issuer`, `destination`, `assertionConsumerServiceUrl`, or `rawXml` is `null`, empty, or whitespace

  • propertyAssertionConsumerServiceUrl
    public string AssertionConsumerServiceUrl { get; init; }

    Gets the Assertion Consumer Service (ACS) endpoint URL where response will be sent.

  • propertyDestination
    public string Destination { get; init; }

    Gets the destination SSO endpoint URI at the Identity Provider.

  • propertyForceAuthn
    public bool ForceAuthn { get; init; }

    Gets a value indicating whether the IdP must re-authenticate the user forcibly.

  • propertyId
    public string Id { get; init; }

    Gets the unique message identifier (e.g. "_guid").

  • propertyIsPassive
    public bool IsPassive { get; init; }

    Gets a value indicating whether authentication must proceed without user interaction (passive).

  • propertyIssueInstant
    public DateTimeOffset IssueInstant { get; init; }

    Gets the issue timestamp.

  • propertyIssuer
    public string Issuer { get; init; }

    Gets the Entity ID of the Service Provider issuer.

  • propertyNameIdFormat
    public Saml2NameIdFormat NameIdFormat { get; init; }

    Gets the requested NameID format policy.

  • propertyProtocolBinding
    public Saml2Binding ProtocolBinding { get; init; }

    Gets the protocol binding for receiving the response.

  • propertyRawXml
    public string RawXml { get; init; }

    Gets the raw XML string of the request.

  • propertyRelayState
    public string? RelayState { get; init; }

    Gets the optional RelayState state string.

record

Saml2AuthnStatement

Ensamblado: EricksonLopez.Security.Saml2
public sealed record Saml2AuthnStatement

Represents a SAML 2.0 AuthnStatement detailing the authentication event.

Miembros (5)

  • constructorSaml2AuthnStatement
    public Saml2AuthnStatement(DateTimeOffset authnInstant, string? sessionIndex = null, DateTimeOffset? sessionNotOnOrAfter = null, string? authnContextClassRef = null)

    Initializes a new instance of the `Saml2AuthnStatement` record with the specified authentication event details.

    authnInstant: DateTimeOffset
    The instant at which the authentication took place at the Identity Provider.
    sessionIndex: string?
    The optional session index identifier assigned by the Identity Provider.
    sessionNotOnOrAfter: DateTimeOffset?
    The optional session expiration timestamp.
    authnContextClassRef: string?
    The optional authentication context class reference URI.
  • propertyAuthnContextClassRef
    public string? AuthnContextClassRef { get; init; }

    Gets the authentication context class reference URI (e.g. PasswordProtectedTransport).

  • propertyAuthnInstant
    public DateTimeOffset AuthnInstant { get; init; }

    Gets the instant at which the authentication took place at the IdP.

  • propertySessionIndex
    public string? SessionIndex { get; init; }

    Gets the optional session index identifier assigned by the IdP.

  • propertySessionNotOnOrAfter
    public DateTimeOffset? SessionNotOnOrAfter { get; init; }

    Gets the optional session expiration timestamp.

record

Saml2Conditions

Ensamblado: EricksonLopez.Security.Saml2
public sealed record Saml2Conditions

Represents the validity conditions and audience restrictions for a SAML 2.0 assertion.

Miembros (4)

  • constructorSaml2Conditions
    public Saml2Conditions(DateTimeOffset? notBefore = null, DateTimeOffset? notOnOrAfter = null, IReadOnlyList<string>? audiences = null)

    Initializes a new instance of the `Saml2Conditions` record with optional validity window and audience constraints.

    notBefore: DateTimeOffset?
    The optional earliest instant at which the assertion is valid.
    notOnOrAfter: DateTimeOffset?
    The optional instant at which the assertion expires.
    audiences: IReadOnlyList<string>?
    The optional list of valid audience URIs allowed to consume the assertion.
  • propertyAudiences
    public IReadOnlyList<string> Audiences { get; init; }

    Gets the list of valid audience URIs (Entity IDs) allowed to consume the assertion.

  • propertyNotBefore
    public DateTimeOffset? NotBefore { get; init; }

    Gets the earliest instant at which the assertion is valid.

  • propertyNotOnOrAfter
    public DateTimeOffset? NotOnOrAfter { get; init; }

    Gets the instant at which the assertion expires and is no longer valid.

record

Saml2LogoutRequest

Ensamblado: EricksonLopez.Security.Saml2
public sealed record Saml2LogoutRequest

Represents a SAML 2.0 Single Logout Request message generated by the Service Provider to initiate federated session termination with the Identity Provider.

Miembros (8)

  • constructorSaml2LogoutRequest
    public Saml2LogoutRequest(string id, string issuer, DateTimeOffset issueInstant, string destination, Saml2NameId nameId, string rawXml, string? sessionIndex = null)

    Initializes a new instance of the `Saml2LogoutRequest` record with the specified session termination data.

    id: string
    The unique message identifier.
    issuer: string
    The Entity ID of the Service Provider issuer.
    issueInstant: DateTimeOffset
    The timestamp when the request was generated.
    destination: string
    The destination Single Logout Service (SLS) endpoint at the Identity Provider.
    nameId: Saml2NameId
    The NameID of the principal whose session is being terminated.
    rawXml: string
    The raw XML string representation of the logout request.
    sessionIndex: string?
    The optional session index from the original assertion.

    Exceptions: ArgumentNullException: `nameId` is `null`; ArgumentException: `id`, `issuer`, `destination`, or `rawXml` is `null`, empty, or whitespace

  • propertyDestination
    public string Destination { get; init; }

    Gets the destination Single Logout Service (SLS) endpoint at the IdP.

  • propertyId
    public string Id { get; init; }

    Gets the unique message identifier (e.g. "_guid").

  • propertyIssueInstant
    public DateTimeOffset IssueInstant { get; init; }

    Gets the issue timestamp.

  • propertyIssuer
    public string Issuer { get; init; }

    Gets the Entity ID of the SP issuer.

  • propertyNameId
    public Saml2NameId NameId { get; init; }

    Gets the NameID of the principal whose session is being terminated. Must match the NameID received in the original assertion.

  • propertyRawXml
    public string RawXml { get; init; }

    Gets the raw XML string of the logout request.

  • propertySessionIndex
    public string? SessionIndex { get; init; }

    Gets the optional session index from the original assertion's AuthnStatement. Allows the IdP to terminate the specific session rather than all sessions.

record

Saml2LogoutResponse

Ensamblado: EricksonLopez.Security.Saml2
public sealed record Saml2LogoutResponse

Represents the result of processing a SAML 2.0 Single Logout Response from the Identity Provider.

Miembros (9)

  • constructorSaml2LogoutResponse
    public Saml2LogoutResponse(string id, string issuer, DateTimeOffset issueInstant, string inResponseTo, string statusCode, string rawXml, string? statusMessage = null)

    Initializes a new instance of the `Saml2LogoutResponse` record with the specified response data.

    id: string
    The unique message identifier of the logout response.
    issuer: string
    The issuer Entity ID of the response.
    issueInstant: DateTimeOffset
    The timestamp when the response was issued.
    inResponseTo: string
    The identifier of the original logout request that triggered this response.
    statusCode: string
    The SAML status code URI.
    rawXml: string
    The raw XML string representation of the logout response.
    statusMessage: string?
    The optional status message returned by the Identity Provider.

    Exceptions: ArgumentException: `id`, `issuer`, `inResponseTo`, `statusCode`, or `rawXml` is `null`, empty, or whitespace

  • propertyId
    public string Id { get; init; }

    Gets the unique message identifier of the logout response.

  • propertyInResponseTo
    public string InResponseTo { get; init; }

    Gets the InResponseTo attribute value, which must match the ID of the `Saml2LogoutRequest` that triggered this response.

  • propertyIsSuccess
    public bool IsSuccess { get; }

    Gets a value indicating whether the logout was successful. `true` when `StatusCode` ends with "Success"; otherwise, `false`.

  • propertyIssueInstant
    public DateTimeOffset IssueInstant { get; init; }

    Gets the issue timestamp.

  • propertyIssuer
    public string Issuer { get; init; }

    Gets the issuer Entity ID of the response (IdP Entity ID).

  • propertyRawXml
    public string RawXml { get; init; }

    Gets the raw XML of the logout response.

  • propertyStatusCode
    public string StatusCode { get; init; }

    Gets the SAML status code URI (e.g., urn:oasis:names:tc:SAML:2.0:status:Success).

  • propertyStatusMessage
    public string? StatusMessage { get; init; }

    Gets an optional status message from the IdP.

record

Saml2NameId

Ensamblado: EricksonLopez.Security.Saml2
public sealed record Saml2NameId

Represents a SAML 2.0 NameID element containing the principal's identifier.

Miembros (5)

  • constructorSaml2NameId
    public Saml2NameId(string value, Saml2NameIdFormat format = Saml2NameIdFormat.Unspecified, string? nameQualifier = null, string? spNameQualifier = null)

    Initializes a new instance of the `Saml2NameId` record with the specified identifier and optional qualifiers.

    value: string
    The NameID value string.
    format: Saml2NameIdFormat
    The NameID format identifier.
    nameQualifier: string?
    The optional NameQualifier string.
    spNameQualifier: string?
    The optional SPNameQualifier string.

    Exceptions: ArgumentException: `value` is `null`, empty, or whitespace

  • propertyFormat
    public Saml2NameIdFormat Format { get; init; }

    Gets the NameID format identifier.

  • propertyNameQualifier
    public string? NameQualifier { get; init; }

    Gets the optional NameQualifier string.

  • propertySpNameQualifier
    public string? SpNameQualifier { get; init; }

    Gets the optional SPNameQualifier string.

  • propertyValue
    public string Value { get; init; }

    Gets the NameID value string.

class

Saml2Options

Ensamblado: EricksonLopez.Security.Saml2
public sealed class Saml2Options

Specifies configuration options for SAML 2.0 Service Provider operations.

Miembros (19)

  • propertyAllowIdpInitiatedSso
    public bool AllowIdpInitiatedSso { get; set; }

    Gets or sets a value indicating whether IdP-initiated SSO responses (responses without `InResponseTo`) are accepted.

    Disabled by default for security. When enabled, assertion replay protection is enforced via an assertion ID cache.

  • propertyAllowedClockSkew
    public TimeSpan AllowedClockSkew { get; set; }

    Gets or sets the allowable clock skew for assertion timestamp verification.

  • propertyAssertionConsumerServiceUrl
    public string AssertionConsumerServiceUrl { get; set; }

    Gets or sets the Assertion Consumer Service (ACS) callback URL on this Service Provider.

  • propertyAuthnRequestBinding
    public Saml2Binding AuthnRequestBinding { get; set; }

    Gets or sets the protocol binding for AuthnRequests (default is HttpRedirect).

  • propertyDefaultNameIdFormat
    public Saml2NameIdFormat DefaultNameIdFormat { get; set; }

    Gets or sets the requested NameID format.

  • propertyIdpEntityId
    public string IdpEntityId { get; set; }

    Gets or sets the Identity Provider Entity ID (URI).

  • propertyIdpInitiatedSsoMaxAssertionAge
    public TimeSpan IdpInitiatedSsoMaxAssertionAge { get; set; }

    Gets or sets the maximum age of an assertion that is acceptable for IdP-initiated SSO. Used as the replay cache TTL window. Default is 5 minutes.

  • propertyIdpSigningCertificate
    public X509Certificate2? IdpSigningCertificate { get; set; }

    Gets or sets the IdP signing certificate for verifying digital signatures on responses and assertions.

  • propertyIdpSingleLogoutUrl
    public string? IdpSingleLogoutUrl { get; set; }

    Gets or sets the Identity Provider Single Logout Service (SLS) URL. Required when using `CreateLogoutRequest()` to initiate SP-initiated SLO.

  • propertyIdpSingleSignOnUrl
    public string IdpSingleSignOnUrl { get; set; }

    Gets or sets the Identity Provider Single Sign-On (SSO) destination URL.

  • propertyNameIdClaimType
    public string NameIdClaimType { get; set; }

    Gets or sets the claim type for mapping the NameID (default is ClaimTypes.NameIdentifier).

  • propertyRequireAssertionExpiration
    public bool RequireAssertionExpiration { get; set; }

    Gets or sets a value indicating whether assertion conditions must strictly contain a NotOnOrAfter expiration attribute.

    The default is `true` per SAML 2.0 Core Section 2.5.1.2.

  • propertyRequireSignedMessages
    public bool RequireSignedMessages { get; set; }

    Gets or sets a value indicating whether inbound assertions or responses must be signed.

  • propertySignAuthnRequests
    public bool SignAuthnRequests { get; set; }

    Gets or sets a value indicating whether outgoing AuthnRequests must be digitally signed.

  • propertySignLogoutRequests
    public bool SignLogoutRequests { get; set; }

    Gets or sets a value indicating whether outgoing `<samlp:LogoutRequest>` messages must be digitally signed.

    Requires `SpSigningCertificate` to be configured.

  • propertySpDecryptionCertificate
    public X509Certificate2? SpDecryptionCertificate { get; set; }

    Gets or sets the SP decryption certificate for decrypting `<saml:EncryptedAssertion>` payloads.

  • propertySpEntityId
    public string SpEntityId { get; set; }

    Gets or sets the Service Provider Entity ID (URI).

  • propertySpSigningCertificate
    public X509Certificate2? SpSigningCertificate { get; set; }

    Gets or sets the SP signing certificate for signing outgoing `AuthnRequest` messages.

  • propertySpSingleLogoutUrl
    public string? SpSingleLogoutUrl { get; set; }

    Gets or sets the Service Provider Single Logout Service (SLS) callback URL. This is where the IdP sends the `<samlp:LogoutResponse>`.

record

Saml2RequestId

Ensamblado: EricksonLopez.Security.Saml2
public readonly record struct Saml2RequestId

Represents a strongly typed SAML 2.0 request identifier.

Miembros (5)

  • constructorSaml2RequestId
    public Saml2RequestId(string value)

    Initializes a new instance of the `Saml2RequestId` struct.

    value: string
    The SAML 2.0 request ID string.

    Exceptions: ArgumentException: Thrown when `value` is null or whitespace

  • methodToString
    public override string ToString()

    Inherits documentation from base type or interface.

  • methodimplicit operator Saml2RequestId
    public static implicit operator Saml2RequestId(string value)

    Converts a string to a `Saml2RequestId`.

    value: string
  • methodimplicit operator string
    public static implicit operator string(Saml2RequestId id)

    Converts a `Saml2RequestId` to its string value.

    id: Saml2RequestId
  • propertyValue
    public string Value { get; }

    Gets the string representation of the request ID.

record

Saml2Response

Ensamblado: EricksonLopez.Security.Saml2
public sealed record Saml2Response

Represents a parsed SAML 2.0 Response message.

Miembros (9)

  • constructorSaml2Response
    public Saml2Response(string id, DateTimeOffset issueInstant, string issuer, Saml2Status status, string rawXml, string? inResponseTo = null, string? destination = null, IReadOnlyList<Saml2Assertion>? assertions = null)

    Initializes a new instance of the `Saml2Response` record with the specified response data.

    id: string
    The unique identifier of the SAML response.
    issueInstant: DateTimeOffset
    The timestamp when the response was issued.
    issuer: string
    The Entity ID of the issuing Identity Provider.
    status: Saml2Status
    The status code and message.
    rawXml: string
    The raw XML string representation of the response.
    inResponseTo: string?
    The optional identifier of the request to which this is a response.
    destination: string?
    The optional intended recipient destination URI.
    assertions: IReadOnlyList<Saml2Assertion>?
    The optional collection of unencrypted assertions contained in the response.

    Exceptions: ArgumentNullException: `status` is `null`; ArgumentException: `id`, `issuer`, or `rawXml` is `null`, empty, or whitespace

  • propertyAssertions
    public IReadOnlyList<Saml2Assertion> Assertions { get; init; }

    Gets the collection of unencrypted assertions contained in the response.

  • propertyDestination
    public string? Destination { get; init; }

    Gets the intended recipient destination URI of the response.

  • propertyId
    public string Id { get; init; }

    Gets the unique ID of the SAML response.

  • propertyInResponseTo
    public string? InResponseTo { get; init; }

    Gets the optional ID of the request to which this is a response (InResponseTo).

  • propertyIssueInstant
    public DateTimeOffset IssueInstant { get; init; }

    Gets the issue instant of the response.

  • propertyIssuer
    public string Issuer { get; init; }

    Gets the Entity ID of the issuing Identity Provider.

  • propertyRawXml
    public string RawXml { get; init; }

    Gets the raw XML string of the response.

  • propertyStatus
    public Saml2Status Status { get; init; }

    Gets the status code and message.

record

Saml2Status

Ensamblado: EricksonLopez.Security.Saml2
public sealed record Saml2Status

Represents the status payload of a SAML 2.0 response.

Miembros (5)

  • constructorSaml2Status
    public Saml2Status(Saml2StatusCode code, string? subCode = null, string? message = null)

    Initializes a new instance of the `Saml2Status` record with the specified status code and optional details.

    code: Saml2StatusCode
    The primary status code.
    subCode: string?
    The optional secondary sub-status code URI string.
    message: string?
    The optional human-readable status message from the Identity Provider.
  • propertyCode
    public Saml2StatusCode Code { get; init; }

    Gets the primary status code.

  • propertyIsSuccess
    public bool IsSuccess { get; }

    Gets a value indicating whether the status code indicates successful authentication.

  • propertyMessage
    public string? Message { get; init; }

    Gets the optional human-readable status message from the IdP.

  • propertySubCode
    public string? SubCode { get; init; }

    Gets the optional secondary sub-status code URI string.

record

Saml2Subject

Ensamblado: EricksonLopez.Security.Saml2
public sealed record Saml2Subject

Represents a SAML 2.0 Subject containing the principal identifier and confirmation data.

Miembros (3)

  • constructorSaml2Subject
    public Saml2Subject(Saml2NameId nameId, Saml2SubjectConfirmation? confirmation = null)

    Initializes a new instance of the `Saml2Subject` record with the specified NameID and optional confirmation.

    nameId: Saml2NameId
    The subject's NameID identifier.
    confirmation: Saml2SubjectConfirmation?
    The optional subject confirmation details.

    Exceptions: ArgumentNullException: `nameId` is `null`

  • propertyConfirmation
    public Saml2SubjectConfirmation? Confirmation { get; init; }

    Gets the subject confirmation details (typically bearer confirmation).

  • propertyNameId
    public Saml2NameId NameId { get; init; }

    Gets the subject's NameID identifier.

record

Saml2SubjectConfirmation

Ensamblado: EricksonLopez.Security.Saml2
public sealed record Saml2SubjectConfirmation

Represents a SAML 2.0 SubjectConfirmation element defining the mechanism for verifying the subject.

Miembros (5)

  • constructorSaml2SubjectConfirmation
    public Saml2SubjectConfirmation(string method, string? recipient = null, string? inResponseTo = null, DateTimeOffset? notOnOrAfter = null)

    Initializes a new instance of the `Saml2SubjectConfirmation` record with the specified confirmation method and optional constraints.

    method: string
    The confirmation method URI (e.g., bearer).
    recipient: string?
    The optional recipient URL.
    inResponseTo: string?
    The optional InResponseTo request identifier.
    notOnOrAfter: DateTimeOffset?
    The optional timestamp limit after which the confirmation is invalid.

    Exceptions: ArgumentException: `method` is `null`, empty, or whitespace

  • propertyInResponseTo
    public string? InResponseTo { get; init; }

    Gets the optional InResponseTo request ID.

  • propertyMethod
    public string Method { get; init; }

    Gets the confirmation method URI (e.g. `urn:oasis:names:tc:SAML:2.0:cm:bearer`).

  • propertyNotOnOrAfter
    public DateTimeOffset? NotOnOrAfter { get; init; }

    Gets the optional NotOnOrAfter timestamp limit.

  • propertyRecipient
    public string? Recipient { get; init; }

    Gets the optional Recipient URL (Assertion Consumer Service URL).

EricksonLopez.Security.Saml2.Services#

2
class

InMemorySaml2ReplayCache

Ensamblado: EricksonLopez.Security.Saml2
public sealed class InMemorySaml2ReplayCache : ISaml2ReplayCache
Implementa: ISaml2ReplayCache

Thread-safe in-memory singleton implementation of `ISaml2ReplayCache`.

Miembros (5)

  • constructorInMemorySaml2ReplayCache
    public InMemorySaml2ReplayCache(TimeProvider? timeProvider = null, int maxCapacity = 50_000)

    Initializes a new instance of the `InMemorySaml2ReplayCache` class.

    timeProvider: TimeProvider?
    The optional time provider.
    maxCapacity: int
    Maximum capacity before forced pruning (default 50,000).
  • methodContainsAsync
    public Task<bool> ContainsAsync(string assertionId, CancellationToken cancellationToken = default)

    Checks whether an assertion ID is currently present in the cache and unexpired.

    assertionId: string
    The unique ID of the SAML assertion.
    cancellationToken: CancellationToken
    A token to cancel the operation.

    Retorna: `true` if the assertion ID exists in the cache; otherwise `false`.

  • methodPrune
    public void Prune()

    Prunes expired entries and trims excess entries over `MaxCapacity`.

  • methodTryAddAsync
    public Task<bool> TryAddAsync(string assertionId, DateTimeOffset expiration, CancellationToken cancellationToken = default)

    Attempts to add an assertion ID to the cache with an expiration timestamp.

    assertionId: string
    The unique ID of the SAML assertion.
    expiration: DateTimeOffset
    The UTC timestamp when the assertion expires.
    cancellationToken: CancellationToken
    A token to cancel the operation.

    Retorna: `true` if the assertion ID was newly added; `false` if it was already processed (replay detected).

  • propertyMaxCapacity
    public int MaxCapacity { get; set; }

    Gets or sets the maximum capacity before forced pruning (default 50,000).

class

Saml2Service

Ensamblado: EricksonLopez.Security.Saml2
public sealed class Saml2Service : ISaml2Service
Implementa: ISaml2Service

Provides SAML 2.0 Web Browser Single Sign-On operations, message generation, and cryptographic verification.

Miembros (9)

  • constructorSaml2Service
    public Saml2Service(IOptions<Saml2Options> options, ISaml2XswValidator xswValidator, ISaml2SignatureValidator signatureValidator, ISaml2AssertionDecryptor assertionDecryptor, ISaml2ClaimsMapper claimsMapper, ILogger<Saml2Service>? logger = null, TimeProvider? timeProvider = null)

    Initializes a new instance of the `Saml2Service` class with required security validators and configuration.

    options: IOptions<Saml2Options>
    The configured SAML 2.0 options.
    xswValidator: ISaml2XswValidator
    The XML Signature Wrapping (XSW) validator.
    signatureValidator: ISaml2SignatureValidator
    The SAML signature validator.
    assertionDecryptor: ISaml2AssertionDecryptor
    The encrypted assertion decryptor.
    claimsMapper: ISaml2ClaimsMapper
    The SAML attribute to claims mapper.
    logger: ILogger<Saml2Service>?
    The optional logger instance.
    timeProvider: TimeProvider?
    The optional time provider instance.
  • constructorSaml2Service
    public Saml2Service(IOptions<Saml2Options> options, ISaml2XswValidator xswValidator, ISaml2SignatureValidator signatureValidator, ISaml2AssertionDecryptor assertionDecryptor, ISaml2ClaimsMapper claimsMapper, ISaml2ReplayCache? replayCache, ILogger<Saml2Service>? logger = null, TimeProvider? timeProvider = null)

    Initializes a new instance of the `Saml2Service` class with replay cache.

    options: IOptions<Saml2Options>
    xswValidator: ISaml2XswValidator
    signatureValidator: ISaml2SignatureValidator
    assertionDecryptor: ISaml2AssertionDecryptor
    claimsMapper: ISaml2ClaimsMapper
    replayCache: ISaml2ReplayCache?
    logger: ILogger<Saml2Service>?
    timeProvider: TimeProvider?
  • methodCreateAuthnRequest
    public Saml2AuthnRequest CreateAuthnRequest(string? relayState = null)

    Generates a signed or unsigned `Saml2AuthnRequest` XML message to initiate SP-initiated SSO.

    relayState: string?
    The optional opaque RelayState string.

    Retorna: A new `Saml2AuthnRequest` model.

  • methodCreateLogoutRequest
    public Saml2LogoutRequest CreateLogoutRequest(Saml2NameId nameId, string? sessionIndex = null, string? relayState = null)

    Creates a `<samlp:LogoutRequest>` XML message to initiate SP-initiated Single Logout.

    nameId: Saml2NameId
    The NameID of the principal whose session should be terminated.
    sessionIndex: string?
    The optional SessionIndex from the original assertion's AuthnStatement.
    relayState: string?
    The optional opaque RelayState string.

    Retorna: A new `Saml2LogoutRequest` model.

  • methodCreateLogoutResponse
    public Saml2LogoutResponse CreateLogoutResponse(string inResponseTo, string destination, bool success = true)

    Creates a `<samlp:LogoutResponse>` XML message in response to an IdP-initiated `<samlp:LogoutRequest>` (for SP-side SLO response).

    inResponseTo: string
    The ID of the incoming IdP LogoutRequest.
    destination: string
    The IdP's SLO response URL.
    success: bool
    A value indicating whether the SP successfully terminated the local session.

    Retorna: A `Saml2LogoutResponse` model containing the SP's SLO response XML.

  • methodGenerateSpMetadata
    public string GenerateSpMetadata()

    Generates an SP Metadata XML document that describes the Service Provider endpoints, capabilities, and certificates to federate with Identity Providers.

    Retorna: A well-formed `<md:EntityDescriptor>` XML string compliant with the SAML 2.0 Metadata Specification (saml-metadata-2.0-os).

  • methodProcessIdpInitiatedResponseAsync
    public async Task<Result<Saml2AuthenticationResult>> ProcessIdpInitiatedResponseAsync(string samlResponseXml, CancellationToken cancellationToken = default)

    Processes an IdP-initiated SAML 2.0 Response (unsolicited response without `InResponseTo`).

    samlResponseXml: string
    The raw XML or Base64-encoded SAML Response string from the IdP.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a result containing the authenticated principal and assertion on success.

    Security note: IdP-initiated SSO is inherently less secure than SP-initiated SSO because there is no request correlation. Enforces assertion ID replay protection to prevent assertion reuse attacks. `Saml2Options.AllowIdpInitiatedSso` must be set to `true` to enable this flow.

  • methodProcessLogoutResponseAsync
    public Task<Result<Saml2LogoutResponse>> ProcessLogoutResponseAsync(string samlLogoutResponseXml, string expectedInResponseTo, CancellationToken cancellationToken = default)

    Validates an incoming `<samlp:LogoutResponse>` from the Identity Provider. Verifies signature, status code, and `InResponseTo` correlation.

    samlLogoutResponseXml: string
    The raw XML or Base64-encoded LogoutResponse string.
    expectedInResponseTo: string
    The ID of the `Saml2LogoutRequest` this is a response to.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a result containing the parsed `Saml2LogoutResponse` on success.

  • methodProcessSpInitiatedResponseAsync
    public async Task<Result<Saml2AuthenticationResult>> ProcessSpInitiatedResponseAsync(string samlResponseXml, Saml2RequestId expectedInResponseTo, CancellationToken cancellationToken = default)

    Processes an SP-initiated SAML 2.0 Response with strongly typed expected request ID correlation.

    samlResponseXml: string
    The raw XML or Base64-encoded SAML Response string.
    expectedInResponseTo: Saml2RequestId
    The strongly typed expected request ID.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A result containing the authenticated principal and assertion on success.

EricksonLopez.Security.Saml2.Xsw#

1
class

Saml2XswValidator

Ensamblado: EricksonLopez.Security.Saml2
public sealed class Saml2XswValidator : ISaml2XswValidator
Implementa: ISaml2XswValidator

Validates XML Signature Wrapping (XSW 1..8) defenses for SAML 2.0 messages.

Notas:

Enforces strict single-assertion integrity, duplicate ID prevention, and signed reference binding.

Miembros (1)

  • methodValidateAndExtractAssertion
    public Result<XmlElement> ValidateAndExtractAssertion(XmlDocument document)

    Validates the XML document structure to ensure the verified signed element matches the exact element consumed by the business logic, rejecting any malicious signature wrapping or element injection.

    document: XmlDocument
    The XML document containing the SAML response.

    Retorna: A result containing the validated canonical assertion XML element on success.

EricksonLopez.Security.Secrets#

6
class

AesGcmSecretProtector

Ensamblado: EricksonLopez.Security
public sealed class AesGcmSecretProtector : ISecretProtector
Implementa: ISecretProtector

Provides an envelope-based secret protector that encrypts sensitive payloads with AES-256-GCM using active keys from `IEncryptionKeyProvider` and produces tamper-resistant binary `SecurityEnvelope` payloads.

Miembros (8)

  • constructorAesGcmSecretProtector
    public AesGcmSecretProtector(IEncryptionKeyProvider keyProvider, IAuthenticatedEncryptionEngine? engine = null, ISecurityEnvelopeSerializer? serializer = null)

    Initializes a new instance of the `AesGcmSecretProtector` class.

    keyProvider: IEncryptionKeyProvider
    The encryption key provider.
    engine: IAuthenticatedEncryptionEngine?
    The optional authenticated encryption engine (defaults to AES-GCM).
    serializer: ISecurityEnvelopeSerializer?
    The optional binary envelope serializer.

    Exceptions: ArgumentNullException: `keyProvider` is `null`

  • methodProtect
    public Result<byte[]> Protect(ReadOnlySpan<byte> secret, KeyPurpose purpose = KeyPurpose.SecretProtection, AuthenticatedContext expectedAssociatedData = default)

    Encrypts and authenticates a plaintext secret span into a newly allocated protected payload.

    secret: ReadOnlySpan<byte>
    Plaintext secret byte span.
    purpose: KeyPurpose
    Cryptographic key purpose for encryption (defaults to `KeyPurpose.SecretProtection`).
    expectedAssociatedData: AuthenticatedContext
    Optional authenticated associated data bound to the envelope.

    Retorna: A `Result<T>` containing the serialized protected binary envelope on success.

  • methodProtectAsync
    public async ValueTask<Result<byte[]>> ProtectAsync(ReadOnlyMemory<byte> secret, KeyPurpose purpose = KeyPurpose.SecretProtection, AuthenticatedContext expectedAssociatedData = default, CancellationToken cancellationToken = default)

    Encrypts and authenticates a secret byte buffer into a protected cryptographic envelope payload.

    secret: ReadOnlyMemory<byte>
    Plaintext secret memory.
    purpose: KeyPurpose
    Cryptographic key purpose (defaults to `KeyPurpose.SecretProtection`).
    expectedAssociatedData: AuthenticatedContext
    Optional authenticated associated data.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the serialized protected binary envelope on success.

  • methodProtectToBase64Url
    public Result<string> ProtectToBase64Url(ReadOnlySpan<byte> secret, KeyPurpose purpose = KeyPurpose.SecretProtection, AuthenticatedContext expectedAssociatedData = default)

    Encrypts `secret` using AES-256-GCM and encodes the serialized envelope as canonical unpadded RFC 4648 §5 Base64Url.

    secret: ReadOnlySpan<byte>
    The plaintext secret bytes.
    purpose: KeyPurpose
    The cryptographic key purpose.
    expectedAssociatedData: AuthenticatedContext
    Optional external authenticated associated data.

    Retorna: A `Result<TValue>` containing the canonical Base64Url ciphertext envelope.

  • methodUnprotect
    public Result<byte[]> Unprotect(ReadOnlySpan<byte> protectedData, AuthenticatedContext expectedAssociatedData = default)

    Decrypts and authenticates a protected envelope span back into plaintext secret bytes.

    protectedData: ReadOnlySpan<byte>
    Protected binary envelope byte span.
    expectedAssociatedData: AuthenticatedContext
    Optional authenticated associated data to verify against the envelope.

    Retorna: A `Result<T>` containing the decrypted plaintext byte array on success.

  • methodUnprotectAsync
    public async ValueTask<Result<byte[]>> UnprotectAsync(ReadOnlyMemory<byte> protectedData, AuthenticatedContext expectedAssociatedData = default, CancellationToken cancellationToken = default)

    Decrypts and authenticates a protected cryptographic envelope payload back into plaintext secret bytes.

    protectedData: ReadOnlyMemory<byte>
    Protected binary envelope memory.
    expectedAssociatedData: AuthenticatedContext
    Optional authenticated associated data to verify.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the decrypted plaintext byte array on success.

    Memory Note (SP-04): The returned `byte[]` contains the decrypted plaintext as a managed heap allocation. Unlike `Memory.SecretBuffer`, a raw `byte[]` cannot be explicitly zeroed by the library because the caller holds the only reference after return. To minimize the plaintext exposure window, callers should: - Process the plaintext and discard the reference as quickly as possible. - Call `CryptographicOperations.ZeroMemory(result);` when finished to scrub the content before the array is collected (best-effort — JIT may optimize away without `[MethodImpl(NoOptimization)]`). A future version (v1.2) will introduce a `UnprotectToSecretBufferAsync` overload returning a `Memory.SecretBuffer` with deterministic zeroing on disposal.

  • methodUnprotectFromBase64Url
    public Result<byte[]> UnprotectFromBase64Url(string base64UrlEnvelope, AuthenticatedContext expectedAssociatedData = default)

    Decodes a canonical unpadded Base64Url ciphertext envelope (rejecting non-zero RFC 4648 §3.5 trailing padding bits) and decrypts the underlying `SecurityEnvelope`.

    base64UrlEnvelope: string
    The canonical unpadded Base64Url envelope string.
    expectedAssociatedData: AuthenticatedContext
    Optional external authenticated associated data.

    Retorna: A `Result<TValue>` containing the decrypted plaintext bytes.

  • methodUnprotectToSecretBufferAsync
    public async ValueTask<Result<ISecretBuffer>> UnprotectToSecretBufferAsync(ReadOnlyMemory<byte> protectedData, AuthenticatedContext expectedAssociatedData = default, CancellationToken cancellationToken = default)

    Decrypts and authenticates a protected cryptographic envelope payload into an unmanaged secret buffer whose memory is zeroized upon disposal.

    protectedData: ReadOnlyMemory<byte>
    Protected binary envelope memory.
    expectedAssociatedData: AuthenticatedContext
    Optional authenticated associated data to verify.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the decrypted `ISecretBuffer` on success.

class

CanonicalBase64Url

Ensamblado: EricksonLopez.Security
public static class CanonicalBase64Url

Provides RFC 4648 §5 Base64Url encoding and strict RFC 4648 §3.5 canonical non-zero trailing padding-bit validation to eliminate ciphertext envelope malleability.

Miembros (3)

  • methodDecodeStrict
    public static byte[] DecodeStrict(ReadOnlySpan<char> chars)

    Decodes a canonical unpadded Base64Url span into bytes, throwing `FormatException` on non-URL-safe characters, explicit `'='` padding, invalid length (`4n+1`), or non-zero RFC 4648 §3.5 trailing bits.

    chars: ReadOnlySpan<char>
    The unpadded Base64Url character span.

    Retorna: The decoded byte array.

    Exceptions: FormatException: The input is not strictly canonical Base64Url.

  • methodEncode
    public static string Encode(ReadOnlySpan<byte> bytes)

    Encodes `bytes` as unpadded Base64Url.

    bytes: ReadOnlySpan<byte>
    The binary payload to encode.

    Retorna: The canonical unpadded Base64Url string.

  • methodHasNonCanonicalPaddingBits
    public static bool HasNonCanonicalPaddingBits(ReadOnlySpan<char> base64Url)

    Determines whether an unpadded Base64Url character span has non-zero trailing unused padding bits (RFC 4648 §3.5) or invalid Base64Url characters.

    base64Url: ReadOnlySpan<char>
    The Base64Url span to inspect.

    Retorna: `true` if non-canonical trailing bits or invalid characters are present; otherwise, `false`.

class

CompositeSecretResolver

Ensamblado: EricksonLopez.Security
public sealed class CompositeSecretResolver : ISecretResolver
Implementa: ISecretResolver

Resolves secrets across multiple backend providers based on URI scheme prefixes.

Notas:

Supports the following URI scheme prefixes: - `env:VARIABLE_NAME` (retrieves from environment variables) - `store:SECRET_NAME` (retrieves from registered `ISecretStore`) - `raw:PLAINTEXT_VALUE` (returns raw value directly)

Miembros (2)

  • constructorCompositeSecretResolver
    public CompositeSecretResolver(ISecretStore secretStore, EnvironmentSecretStore? envStore = null)

    Initializes a new instance of the `CompositeSecretResolver` class.

    secretStore: ISecretStore
    The default secret store.
    envStore: EnvironmentSecretStore?
    The optional environment secret store.

    Exceptions: ArgumentNullException: `secretStore` is `null`

  • methodResolveAsync
    public async ValueTask<Result<Redacted<string>>> ResolveAsync(string secretReference, CancellationToken cancellationToken = default)

    Resolves a secret reference string to its unredacted secret value.

    secretReference: string
    The reference URI or key string.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the secret value.

class

EnvironmentSecretStore

Ensamblado: EricksonLopez.Security
public sealed class EnvironmentSecretStore : ISecretStore
Implementa: ISecretStore

Provides an implementation of `ISecretStore` that reads and writes secrets from environment variables.

Miembros (3)

  • constructorEnvironmentSecretStore
    public EnvironmentSecretStore(string prefix = "")

    Initializes a new instance of the `EnvironmentSecretStore` class.

    prefix: string
    The optional environment variable prefix (e.g., "APP_").
  • methodGetSecretAsync
    public ValueTask<Result<Redacted<string>>> GetSecretAsync(string secretName, CancellationToken cancellationToken = default)

    Retrieves a secret by name as a memory-safe `Redacted<T>` string container.

    secretName: string
    The unique secret key name.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the secret value.

  • methodSetSecretAsync
    public ValueTask<Result> SetSecretAsync(string secretName, string secretValue, CancellationToken cancellationToken = default)

    Sets or updates a secret in the underlying store.

    secretName: string
    The unique secret key name.
    secretValue: string
    The secret value to persist.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating success or failure.

    Security Warning: Environment variables set at `EnvironmentVariableTarget.Process` scope are visible to native libraries in the current process and inherited by child processes spawned via `Process.Start(string)`.

class

VersionedAesGcmSecretProtector

Ensamblado: EricksonLopez.Security
public sealed class VersionedAesGcmSecretProtector : IVersionedSecretProtector, IDisposable
Implementa: IDisposable, IVersionedSecretProtector

Provides versioned text-envelope (`v1.<base64url>`) and binary-envelope AES-256-GCM secret protection with HKDF-SHA256 per-version/per-purpose subkey derivation, external AAD binding, multi-version key rotation, and deterministic `ZeroMemory` buffer scrubbing.

Miembros (33)

  • constructorVersionedAesGcmSecretProtector
    public VersionedAesGcmSecretProtector(IOptions<VersionedSecretProtectorOptions> options)

    Initializes a new instance of the `VersionedAesGcmSecretProtector` class from `IOptions<TOptions>`.

    options: IOptions<VersionedSecretProtectorOptions>
    The configured `VersionedSecretProtectorOptions` wrapper.

    Exceptions: ArgumentNullException: `options` is `null`.

  • constructorVersionedAesGcmSecretProtector
    public VersionedAesGcmSecretProtector(VersionedSecretProtectorOptions options)

    Initializes a new instance of the `VersionedAesGcmSecretProtector` class.

    options: VersionedSecretProtectorOptions
    The configured `VersionedSecretProtectorOptions`.

    Exceptions: ArgumentNullException: `options` is `null`.; ArgumentException: No master keys are configured, a key version is invalid, a key is not 32 bytes, or `VersionedSecretProtectorOptions.HkdfDomainPrefix` is empty.

  • methodDispose
    public void Dispose()

    Scrubs all master encryption key material from memory.

  • methodProtect
    public Result<VersionedSecretEnvelope> Protect(ReadOnlySpan<byte> plaintext, string purpose, AuthenticatedContext associatedData)

    Encrypts and authenticates a plaintext byte span into a versioned `v1.<base64url>` envelope bound to external AAD.

    plaintext: ReadOnlySpan<byte>
    The plaintext secret bytes to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: AuthenticatedContext
    The external authenticated context (AAD) bound to the authentication tag.

    Retorna: A `Result<T>` containing the `VersionedSecretEnvelope` on success.

  • methodProtect
    public Result<VersionedSecretEnvelope> Protect(ReadOnlySpan<byte> plaintext, string purpose, ReadOnlySpan<byte> associatedData)

    Encrypts and authenticates a plaintext byte span into a versioned `v1.<base64url>` envelope bound to external AAD.

    plaintext: ReadOnlySpan<byte>
    The plaintext secret bytes to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: ReadOnlySpan<byte>
    The external authenticated context (AAD) bound to the authentication tag.

    Retorna: A `Result<T>` containing the `VersionedSecretEnvelope` on success.

  • methodProtect
    public Result<VersionedSecretEnvelope> Protect(ReadOnlySpan<byte> plaintext, string purpose, string? associatedDataContext)

    Encrypts and authenticates a plaintext byte span into a versioned `v1.<base64url>` envelope bound to external AAD.

    plaintext: ReadOnlySpan<byte>
    The plaintext secret bytes to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedDataContext: string?

    Retorna: A `Result<T>` containing the `VersionedSecretEnvelope` on success.

  • methodProtectString
    public Result<VersionedSecretEnvelope> ProtectString(string plaintext, string purpose, AuthenticatedContext associatedData)

    Encrypts and authenticates a UTF-8 plaintext secret string into a versioned `v1.<base64url>` envelope, scrubbing intermediate UTF-8 plaintext bytes from memory before returning.

    plaintext: string
    The non-empty plaintext string to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: AuthenticatedContext
    The external authenticated context (AAD) bound to the authentication tag.

    Retorna: A `Result<T>` containing the `VersionedSecretEnvelope` on success.

  • methodProtectString
    public Result<VersionedSecretEnvelope> ProtectString(string plaintext, string purpose, ReadOnlySpan<byte> associatedData)

    Encrypts and authenticates a UTF-8 plaintext secret string into a versioned `v1.<base64url>` envelope, scrubbing intermediate UTF-8 plaintext bytes from memory before returning.

    plaintext: string
    The non-empty plaintext string to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: ReadOnlySpan<byte>
    The external authenticated context (AAD) bound to the authentication tag.

    Retorna: A `Result<T>` containing the `VersionedSecretEnvelope` on success.

  • methodProtectString
    public Result<VersionedSecretEnvelope> ProtectString(string plaintext, string purpose, string? associatedDataContext)

    Encrypts and authenticates a UTF-8 plaintext secret string into a versioned `v1.<base64url>` envelope, scrubbing intermediate UTF-8 plaintext bytes from memory before returning.

    plaintext: string
    The non-empty plaintext string to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedDataContext: string?

    Retorna: A `Result<T>` containing the `VersionedSecretEnvelope` on success.

  • methodProtectStringToBytes
    public Result<byte[]> ProtectStringToBytes(string plaintext, string purpose, AuthenticatedContext associatedData)

    Encrypts and authenticates a UTF-8 plaintext string into a compact binary versioned AEAD payload, scrubbing intermediate plaintext bytes.

    plaintext: string
    The non-empty plaintext string to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: AuthenticatedContext
    The external authenticated context (AAD) bound to the authentication tag.

    Retorna: A `Result<T>` containing the binary versioned AEAD payload on success.

  • methodProtectStringToBytes
    public Result<byte[]> ProtectStringToBytes(string plaintext, string purpose, ReadOnlySpan<byte> associatedData)

    Encrypts and authenticates a UTF-8 plaintext string into a compact binary versioned AEAD payload, scrubbing intermediate plaintext bytes.

    plaintext: string
    The non-empty plaintext string to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: ReadOnlySpan<byte>
    The external authenticated context (AAD) bound to the authentication tag.

    Retorna: A `Result<T>` containing the binary versioned AEAD payload on success.

  • methodProtectStringToBytes
    public Result<byte[]> ProtectStringToBytes(string plaintext, string purpose, string? associatedDataContext)

    Encrypts and authenticates a UTF-8 plaintext string into a compact binary versioned AEAD payload, scrubbing intermediate plaintext bytes.

    plaintext: string
    The non-empty plaintext string to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedDataContext: string?

    Retorna: A `Result<T>` containing the binary versioned AEAD payload on success.

  • methodProtectToBytes
    public Result<byte[]> ProtectToBytes(ReadOnlySpan<byte> plaintext, string purpose, AuthenticatedContext associatedData)

    Encrypts and authenticates a plaintext byte span into a compact binary versioned AEAD payload.

    plaintext: ReadOnlySpan<byte>
    The plaintext secret bytes to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: AuthenticatedContext
    The external authenticated context (AAD) bound to the authentication tag.

    Retorna: A `Result<T>` containing the binary versioned AEAD payload on success.

  • methodProtectToBytes
    public Result<byte[]> ProtectToBytes(ReadOnlySpan<byte> plaintext, string purpose, ReadOnlySpan<byte> associatedData)

    Encrypts and authenticates a plaintext byte span into a compact binary versioned AEAD payload.

    plaintext: ReadOnlySpan<byte>
    The plaintext secret bytes to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: ReadOnlySpan<byte>
    The external authenticated context (AAD) bound to the authentication tag.

    Retorna: A `Result<T>` containing the binary versioned AEAD payload on success.

  • methodProtectToBytes
    public Result<byte[]> ProtectToBytes(ReadOnlySpan<byte> plaintext, string purpose, string? associatedDataContext)

    Encrypts and authenticates a plaintext byte span into a compact binary versioned AEAD payload.

    plaintext: ReadOnlySpan<byte>
    The plaintext secret bytes to protect.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedDataContext: string?

    Retorna: A `Result<T>` containing the binary versioned AEAD payload on success.

  • methodUnprotect
    public Result<byte[]> Unprotect(string ciphertextEnvelope, string purpose, AuthenticatedContext associatedData, int expectedKeyVersion = 0)

    Decrypts and authenticates a `v1.<base64url>` envelope using the reconstructed external AAD and optional expected key version.

    ciphertextEnvelope: string
    The persisted `v1.<base64url>` envelope string.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: AuthenticatedContext
    The external authenticated context (AAD) to verify.
    expectedKeyVersion: int
    Optional expected key version (`> 0` enforces exact header match; `<= 0` accepts any loaded version in the key ring).

    Retorna: A `Result<T>` containing the decrypted plaintext byte array on success.

  • methodUnprotect
    public Result<byte[]> Unprotect(string ciphertextEnvelope, string purpose, ReadOnlySpan<byte> associatedData, int expectedKeyVersion = 0)

    Decrypts and authenticates a `v1.<base64url>` envelope using the reconstructed external AAD and optional expected key version.

    ciphertextEnvelope: string
    The persisted `v1.<base64url>` envelope string.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: ReadOnlySpan<byte>
    The external authenticated context (AAD) to verify.
    expectedKeyVersion: int
    Optional expected key version (`> 0` enforces exact header match; `<= 0` accepts any loaded version in the key ring).

    Retorna: A `Result<T>` containing the decrypted plaintext byte array on success.

  • methodUnprotect
    public Result<byte[]> Unprotect(string ciphertextEnvelope, string purpose, string? associatedDataContext, int expectedKeyVersion = 0)

    Decrypts and authenticates a `v1.<base64url>` envelope using the reconstructed external AAD and optional expected key version.

    ciphertextEnvelope: string
    The persisted `v1.<base64url>` envelope string.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedDataContext: string?
    expectedKeyVersion: int
    Optional expected key version (`> 0` enforces exact header match; `<= 0` accepts any loaded version in the key ring).

    Retorna: A `Result<T>` containing the decrypted plaintext byte array on success.

  • methodUnprotectFromBytes
    public Result<byte[]> UnprotectFromBytes(ReadOnlySpan<byte> ciphertextPayload, string purpose, AuthenticatedContext associatedData, int expectedKeyVersion = 0)

    Decrypts and authenticates a compact binary versioned AEAD payload using external `AuthenticatedContext` AAD.

    ciphertextPayload: ReadOnlySpan<byte>
    The binary versioned AEAD payload produced by `ProtectToBytes(ReadOnlySpan<byte>, string, AuthenticatedContext)`.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: AuthenticatedContext
    The external authenticated context (AAD) to verify.
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted plaintext byte array on success.

  • methodUnprotectFromBytes
    public Result<byte[]> UnprotectFromBytes(ReadOnlySpan<byte> ciphertextPayload, string purpose, ReadOnlySpan<byte> associatedData, int expectedKeyVersion = 0)

    Decrypts and authenticates a compact binary versioned AEAD payload using external `AuthenticatedContext` AAD.

    ciphertextPayload: ReadOnlySpan<byte>
    The binary versioned AEAD payload produced by `ProtectToBytes(ReadOnlySpan<byte>, string, AuthenticatedContext)`.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: ReadOnlySpan<byte>
    The external authenticated context (AAD) to verify.
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted plaintext byte array on success.

  • methodUnprotectFromBytes
    public Result<byte[]> UnprotectFromBytes(ReadOnlySpan<byte> ciphertextPayload, string purpose, string? associatedDataContext, int expectedKeyVersion = 0)

    Decrypts and authenticates a compact binary versioned AEAD payload using external `AuthenticatedContext` AAD.

    ciphertextPayload: ReadOnlySpan<byte>
    The binary versioned AEAD payload produced by `ProtectToBytes(ReadOnlySpan<byte>, string, AuthenticatedContext)`.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedDataContext: string?
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted plaintext byte array on success.

  • methodUnprotectString
    public Result<string> UnprotectString(string ciphertextEnvelope, string purpose, AuthenticatedContext associatedData, int expectedKeyVersion = 0)

    Decrypts and authenticates a `v1.<base64url>` envelope into a UTF-8 string, scrubbing intermediate decrypted byte buffers via `ZeroMemory` before returning.

    ciphertextEnvelope: string
    The persisted `v1.<base64url>` envelope string.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: AuthenticatedContext
    The external authenticated context (AAD) to verify.
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted UTF-8 string on success.

  • methodUnprotectString
    public Result<string> UnprotectString(string ciphertextEnvelope, string purpose, ReadOnlySpan<byte> associatedData, int expectedKeyVersion = 0)

    Decrypts and authenticates a `v1.<base64url>` envelope into a UTF-8 string, scrubbing intermediate decrypted byte buffers via `ZeroMemory` before returning.

    ciphertextEnvelope: string
    The persisted `v1.<base64url>` envelope string.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: ReadOnlySpan<byte>
    The external authenticated context (AAD) to verify.
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted UTF-8 string on success.

  • methodUnprotectString
    public Result<string> UnprotectString(string ciphertextEnvelope, string purpose, string? associatedDataContext, int expectedKeyVersion = 0)

    Decrypts and authenticates a `v1.<base64url>` envelope into a UTF-8 string, scrubbing intermediate decrypted byte buffers via `ZeroMemory` before returning.

    ciphertextEnvelope: string
    The persisted `v1.<base64url>` envelope string.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedDataContext: string?
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted UTF-8 string on success.

  • methodUnprotectStringFromBytes
    public Result<string> UnprotectStringFromBytes(ReadOnlySpan<byte> ciphertextPayload, string purpose, AuthenticatedContext associatedData, int expectedKeyVersion = 0)

    Decrypts and authenticates a compact binary versioned AEAD payload into a UTF-8 string, scrubbing intermediate buffers.

    ciphertextPayload: ReadOnlySpan<byte>
    The binary versioned AEAD payload.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: AuthenticatedContext
    The external authenticated context (AAD) to verify.
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted UTF-8 string on success.

  • methodUnprotectStringFromBytes
    public Result<string> UnprotectStringFromBytes(ReadOnlySpan<byte> ciphertextPayload, string purpose, ReadOnlySpan<byte> associatedData, int expectedKeyVersion = 0)

    Decrypts and authenticates a compact binary versioned AEAD payload into a UTF-8 string, scrubbing intermediate buffers.

    ciphertextPayload: ReadOnlySpan<byte>
    The binary versioned AEAD payload.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: ReadOnlySpan<byte>
    The external authenticated context (AAD) to verify.
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted UTF-8 string on success.

  • methodUnprotectStringFromBytes
    public Result<string> UnprotectStringFromBytes(ReadOnlySpan<byte> ciphertextPayload, string purpose, string? associatedDataContext, int expectedKeyVersion = 0)

    Decrypts and authenticates a compact binary versioned AEAD payload into a UTF-8 string, scrubbing intermediate buffers.

    ciphertextPayload: ReadOnlySpan<byte>
    The binary versioned AEAD payload.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedDataContext: string?
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted UTF-8 string on success.

  • methodUnprotectToSecretBuffer
    public Result<ISecretBuffer> UnprotectToSecretBuffer(string ciphertextEnvelope, string purpose, AuthenticatedContext associatedData, int expectedKeyVersion = 0)

    Decrypts and authenticates a `v1.<base64url>` envelope directly into a zeroizable `ISecretBuffer`.

    ciphertextEnvelope: string
    The persisted `v1.<base64url>` envelope string.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: AuthenticatedContext
    The external authenticated context (AAD) to verify.
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted `ISecretBuffer` on success.

  • methodUnprotectToSecretBuffer
    public Result<ISecretBuffer> UnprotectToSecretBuffer(string ciphertextEnvelope, string purpose, ReadOnlySpan<byte> associatedData, int expectedKeyVersion = 0)

    Decrypts and authenticates a `v1.<base64url>` envelope directly into a zeroizable `ISecretBuffer`.

    ciphertextEnvelope: string
    The persisted `v1.<base64url>` envelope string.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedData: ReadOnlySpan<byte>
    The external authenticated context (AAD) to verify.
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted `ISecretBuffer` on success.

  • methodUnprotectToSecretBuffer
    public Result<ISecretBuffer> UnprotectToSecretBuffer(string ciphertextEnvelope, string purpose, string? associatedDataContext, int expectedKeyVersion = 0)

    Decrypts and authenticates a `v1.<base64url>` envelope directly into a zeroizable `ISecretBuffer`.

    ciphertextEnvelope: string
    The persisted `v1.<base64url>` envelope string.
    purpose: string
    The non-empty cryptographic purpose label used for HKDF subkey domain separation.
    associatedDataContext: string?
    expectedKeyVersion: int
    Optional expected key version.

    Retorna: A `Result<T>` containing the decrypted `ISecretBuffer` on success.

  • propertyActiveKeyVersion
    public int ActiveKeyVersion { get; }

    Gets the currently active master key version used for new encryption operations.

  • propertyIsDisposed
    public bool IsDisposed { get; }

    Gets a value indicating whether this instance has been disposed.

  • propertyRequireAssociatedData
    public bool RequireAssociatedData { get; }

    Gets a value indicating whether non-empty associated data (AAD) is mandatory for all protect and unprotect operations.

class

VersionedSecretProtectorOptions

Ensamblado: EricksonLopez.Security
public sealed class VersionedSecretProtectorOptions

Configures master encryption key versions, mandatory AAD enforcement, and HKDF domain separation for `VersionedAesGcmSecretProtector`.

Miembros (5)

  • methodAddMasterKeyFromEncoded
    public VersionedSecretProtectorOptions AddMasterKeyFromEncoded(int version, string encodedMaterial)

    Decodes and registers a 256-bit master key for `version` from a 64-character hexadecimal string, a Base64 string (at least 32 decoded bytes), or a high-entropy UTF-8 string (at least 32 UTF-8 bytes, hashed via SHA-256 into 32 bytes).

    version: int
    The positive key version (`1..65535`).
    encodedMaterial: string
    The hex, Base64, or high-entropy passphrase material.

    Retorna: This `VersionedSecretProtectorOptions` instance for fluent configuration.

    Exceptions: ArgumentOutOfRangeException: `version` is outside `1..65535`.; ArgumentException: `encodedMaterial` is null, whitespace, or contains fewer than 32 bytes of material.

  • propertyActiveKeyVersion
    public int? ActiveKeyVersion { get; set; }

    Gets or sets the active key version used for new encryption operations. When `null`, the highest registered version in `MasterKeys` is selected automatically.

  • propertyHkdfDomainPrefix
    public string HkdfDomainPrefix { get; set; }

    Gets or sets the HKDF `info` domain-separation prefix (`{HkdfDomainPrefix}:{PURPOSE}`). Defaults to `"ericksonlopez.aead.v1"`.

  • propertyMasterKeys
    public IDictionary<int, byte[]> MasterKeys { get; }

    Gets the versioned 256-bit (32-byte) master encryption keys indexed by version (`1..65535`).

  • propertyRequireAssociatedData
    public bool RequireAssociatedData { get; set; }

    Gets or sets a value indicating whether non-empty associated data (AAD) is mandatory for all protect and unprotect operations. Defaults to `true` (fail-closed rejection of empty AAD).

EricksonLopez.Security.Testing.Assertions#

1
class

SecurityAssert

Ensamblado: EricksonLopez.Security.Testing
public static class SecurityAssert

Provides security verification assertions for testing cryptographic boundaries, redaction, and memory wiping.

Miembros (3)

  • methodAreConstantTimeEqual
    public static void AreConstantTimeEqual(ReadOnlySpan<byte> expected, ReadOnlySpan<byte> actual)

    Verifies that two byte spans are equal in constant time.

    expected: ReadOnlySpan<byte>
    The expected byte span.
    actual: ReadOnlySpan<byte>
    The actual byte span.

    Exceptions: InvalidOperationException: The byte spans are not equal in constant-time comparison

  • methodIsDisposed
    public static void IsDisposed(ISecretBuffer buffer)

    Verifies that an `ISecretBuffer` is wiped and disposed.

    buffer: ISecretBuffer
    The secret buffer to verify.

    Exceptions: ArgumentNullException: `buffer` is `null`; InvalidOperationException: `buffer` has not been disposed

  • methodIsRedacted
    public static void IsRedacted(object sensitiveObject, string expectedMask = "")

    Verifies that a sensitive object correctly redacts its value in `object.ToString`.

    sensitiveObject: object
    The sensitive object to evaluate.
    expectedMask: string
    The expected redaction substring (defaults to "REDACTED").

    Exceptions: ArgumentNullException: `sensitiveObject` is `null`; InvalidOperationException: `sensitiveObject` failed the redaction check

EricksonLopez.Security.Testing.Builders#

2
class

Fido2AttestationTestBuilder

Ensamblado: EricksonLopez.Security.Testing
public sealed class Fido2AttestationTestBuilder

Provides a fluent test builder for constructing synthetic FIDO2/WebAuthn attestation payloads, keys, and statements.

Miembros (12)

  • methodBuild
    public (AttestationStatement Statement, AuthenticatorData AuthData, byte[] ClientDataHash) Build()

    Builds the signed attestation statement, authenticator data, and client data hash.

    Retorna: A tuple containing the attestation statement, authenticator data, and client data hash.

  • methodBuildCborAttestationObject
    public static byte[] BuildCborAttestationObject(byte[] authData, string fmt = "", Action<CborWriter>? customAttStmtWriter = null)

    Builds a CBOR-encoded attestation object from the given authData and statement writer.

    authData: byte[]
    The raw authenticator data bytes.
    fmt: string
    The attestation statement format (defaults to "none").
    customAttStmtWriter: Action<CborWriter>?
    The optional custom writer for the attStmt map.

    Retorna: The CBOR encoded attestation object bytes.

    Exceptions: ArgumentNullException: `authData` is `null`

  • methodBuildRawAssertionResponse
    public (AuthenticatorAssertionRawResponse RawResponse, CosePublicKey PublicKey) BuildRawAssertionResponse(byte[] challenge, string rpId = "", string origin = "", byte[]? userHandle = null)

    Builds a full synthetic AuthenticatorAssertionRawResponse for ceremony authentication testing.

    challenge: byte[]
    The challenge bytes.
    rpId: string
    The relying party ID.
    origin: string
    The expected origin.
    userHandle: byte[]?
    The optional user handle.

    Retorna: A tuple of raw assertion response and public key.

  • methodBuildRawAttestationResponse
    public (AuthenticatorAttestationRawResponse RawResponse, CosePublicKey PublicKey) BuildRawAttestationResponse(byte[] challenge, string rpId = "", string origin = "")

    Builds a full synthetic AuthenticatorAttestationRawResponse for ceremony testing.

    challenge: byte[]
    The challenge bytes.
    rpId: string
    The relying party ID.
    origin: string
    The expected origin.

    Retorna: A tuple of raw attestation response and public key.

  • methodWithAaguid
    public Fido2AttestationTestBuilder WithAaguid(Guid aaguid)

    Sets the AAGUID.

    aaguid: Guid
    The authenticator attestation GUID.

    Retorna: The builder instance.

  • methodWithClientDataHash
    public Fido2AttestationTestBuilder WithClientDataHash(byte[] clientDataHash)

    Sets the client data hash.

    clientDataHash: byte[]
    The client data hash bytes.

    Retorna: The builder instance.

    Exceptions: ArgumentNullException: `clientDataHash` is `null`

  • methodWithCredentialId
    public Fido2AttestationTestBuilder WithCredentialId(byte[] credentialId)

    Sets the credential identifier.

    credentialId: byte[]
    The credential identifier bytes.

    Retorna: The builder instance.

    Exceptions: ArgumentNullException: `credentialId` is `null`

  • methodWithEc2Key
    public Fido2AttestationTestBuilder WithEc2Key(CoseEllipticCurve curve, CoseAlgorithmIdentifier algorithm)

    Configures the key as EC2 with specified curve and algorithm.

    curve: CoseEllipticCurve
    The COSE elliptic curve.
    algorithm: CoseAlgorithmIdentifier
    The COSE algorithm identifier.

    Retorna: The builder instance.

  • methodWithFlags
    public Fido2AttestationTestBuilder WithFlags(AuthenticatorDataFlags flags)

    Sets the authenticator flags.

    flags: AuthenticatorDataFlags
    The authenticator flags.

    Retorna: The builder instance.

  • methodWithFormat
    public Fido2AttestationTestBuilder WithFormat(string format)

    Sets the format name.

    format: string
    The attestation format string.

    Retorna: The builder instance.

  • methodWithRsaKey
    public Fido2AttestationTestBuilder WithRsaKey(CoseAlgorithmIdentifier algorithm)

    Configures the key as RSA with specified algorithm.

    algorithm: CoseAlgorithmIdentifier
    The COSE algorithm identifier.

    Retorna: The builder instance.

  • methodWithSignCount
    public Fido2AttestationTestBuilder WithSignCount(uint signCount)

    Sets the signature counter.

    signCount: uint
    The signature counter value.

    Retorna: The builder instance.

class

SamlTestMessageBuilder

Ensamblado: EricksonLopez.Security.Testing
public sealed class SamlTestMessageBuilder

Provides a fluent builder for constructing valid or tampered SAML 2.0 XML responses and assertions for deterministic testing.

Miembros (22)

  • methodBuildXml
    public string BuildXml()

    Builds the complete SAML 2.0 XML string representation.

    Retorna: The complete SAML 2.0 XML string representation.

  • methodWithAssertionId
    public SamlTestMessageBuilder WithAssertionId(string assertionId)

    Sets the assertion ID.

    assertionId: string
    The assertion element identifier.

    Retorna: The current builder instance for fluent chaining.

  • methodWithAssertionIssuer
    public SamlTestMessageBuilder WithAssertionIssuer(string assertionIssuer)

    Sets a divergent assertion issuer to test issuer mismatch scenarios.

    assertionIssuer: string
    The divergent assertion issuer entity ID.

    Retorna: The current builder instance for fluent chaining.

  • methodWithAttribute
    public SamlTestMessageBuilder WithAttribute(string name, string value, string? friendlyName = null)

    Adds a SAML attribute statement with a single value.

    name: string
    The attribute name URI or identifier.
    value: string
    The single attribute value string.
    friendlyName: string?
    The optional friendly name for the attribute.

    Retorna: The current builder instance for fluent chaining.

  • methodWithAttribute
    public SamlTestMessageBuilder WithAttribute(string name, string[] values, string? friendlyName = null)

    Adds a SAML attribute statement with multiple values.

    name: string
    The attribute name URI or identifier.
    values: string[]
    The collection of attribute value strings.
    friendlyName: string?
    The optional friendly name for the attribute.

    Retorna: The current builder instance for fluent chaining.

  • methodWithAudience
    public SamlTestMessageBuilder WithAudience(string audience)

    Sets the audience URI for audience restriction checks.

    audience: string
    Audience restriction URI.

    Retorna: Current builder instance for fluent chaining.

  • methodWithAuthnStatement
    public SamlTestMessageBuilder WithAuthnStatement(DateTimeOffset authnInstant, string? sessionIndex = null)

    Sets the AuthnStatement instant and session index.

    authnInstant: DateTimeOffset
    UTC timestamp when authentication occurred.
    sessionIndex: string?
    Optional session index identifier.

    Retorna: Current builder instance for fluent chaining.

  • methodWithConditions
    public SamlTestMessageBuilder WithConditions(DateTimeOffset notBefore, DateTimeOffset notOnOrAfter)

    Sets the condition validity timestamps.

    notBefore: DateTimeOffset
    Not-before validity UTC timestamp.
    notOnOrAfter: DateTimeOffset
    Not-on-or-after validity UTC timestamp.

    Retorna: Current builder instance for fluent chaining.

  • methodWithDestination
    public SamlTestMessageBuilder WithDestination(string destination)

    Sets the Destination attribute on the Response element.

    destination: string
    The destination URI endpoint attribute.

    Retorna: The current builder instance for fluent chaining.

  • methodWithInResponseTo
    public SamlTestMessageBuilder WithInResponseTo(string inResponseTo)

    Sets the InResponseTo attribute.

    inResponseTo: string
    The identifier of the request message being responded to.

    Retorna: The current builder instance for fluent chaining.

  • methodWithIssueInstant
    public SamlTestMessageBuilder WithIssueInstant(DateTimeOffset issueInstant)

    Sets the issue instant timestamp.

    issueInstant: DateTimeOffset
    Message issue instant UTC timestamp.

    Retorna: Current builder instance for fluent chaining.

  • methodWithIssuer
    public SamlTestMessageBuilder WithIssuer(string issuer)

    Sets the IDP issuer.

    issuer: string
    The identity provider issuer entity ID.

    Retorna: The current builder instance for fluent chaining.

  • methodWithResponseId
    public SamlTestMessageBuilder WithResponseId(string responseId)

    Sets the response element ID.

    responseId: string
    The response element identifier.

    Retorna: The current builder instance for fluent chaining.

  • methodWithSecondaryStatusCode
    public SamlTestMessageBuilder WithSecondaryStatusCode(string secondStatusCode)

    Sets a nested secondary status code (e.g. AuthnFailed).

    secondStatusCode: string
    The nested secondary status code URI.

    Retorna: The current builder instance for fluent chaining.

  • methodWithStatusCode
    public SamlTestMessageBuilder WithStatusCode(string statusCode)

    Sets the top-level status code.

    statusCode: string
    The top-level SAML status code URI.

    Retorna: The current builder instance for fluent chaining.

  • methodWithStatusMessage
    public SamlTestMessageBuilder WithStatusMessage(string statusMessage)

    Sets the status message.

    statusMessage: string
    The human-readable status message text.

    Retorna: The current builder instance for fluent chaining.

  • methodWithSubject
    public SamlTestMessageBuilder WithSubject(string subjectNameId)

    Sets the subject NameID.

    subjectNameId: string
    The subject NameID string value.

    Retorna: The current builder instance for fluent chaining.

  • methodWithSubjectConfirmation
    public SamlTestMessageBuilder WithSubjectConfirmation(string recipient, DateTimeOffset notOnOrAfter)

    Sets SubjectConfirmation data for bearer validation.

    recipient: string
    Expected bearer recipient URI.
    notOnOrAfter: DateTimeOffset
    Expiration UTC timestamp for the bearer confirmation.

    Retorna: Current builder instance for fluent chaining.

  • methodWithoutAssertion
    public SamlTestMessageBuilder WithoutAssertion()

    Omits the assertion element to simulate empty or invalid responses.

    Retorna: The current builder instance for fluent chaining.

  • methodWithoutConditions
    public SamlTestMessageBuilder WithoutConditions()

    Omits the Conditions element to test missing conditions scenarios.

    Retorna: The current builder instance for fluent chaining.

  • methodWithoutStatus
    public SamlTestMessageBuilder WithoutStatus()

    Omits the Status element to test malformed responses.

    Retorna: The current builder instance for fluent chaining.

  • methodWithoutSubject
    public SamlTestMessageBuilder WithoutSubject()

    Omits the Subject element to test missing subject scenarios.

    Retorna: The current builder instance for fluent chaining.

EricksonLopez.Security.Testing.Fakes#

5
class

DeterministicRandomNumberGenerator

Ensamblado: EricksonLopez.Security.Testing
public sealed class DeterministicRandomNumberGenerator : ICryptographicRandomNumberGenerator
Implementa: ICryptographicRandomNumberGenerator

Provides a deterministic implementation of `ICryptographicRandomNumberGenerator` seeded with a pseudo-random generator for reproducible cryptographic tests.

Miembros (4)

  • constructorDeterministicRandomNumberGenerator
    public DeterministicRandomNumberGenerator(int seed = 42)

    Initializes a new instance of the `DeterministicRandomNumberGenerator` class with a fixed seed.

    seed: int
    The deterministic random seed (defaults to 42).
  • methodFill
    public void Fill(Span<byte> destination)

    Fills the destination byte span with cryptographically strong random bytes.

    destination: Span<byte>
    The destination span.
  • methodGetBytes
    public byte[] GetBytes(int count)

    Allocates and fills a byte array with cryptographically strong random bytes.

    count: int
    The number of bytes to generate.

    Retorna: A byte array containing cryptographically strong random bytes.

  • methodGetInt32
    public int GetInt32(int fromInclusive, int toExclusive)

    Generates a cryptographically strong random integer within the specified range.

    fromInclusive: int
    The inclusive lower bound.
    toExclusive: int
    The exclusive upper bound.

    Retorna: A cryptographically strong random integer within the specified range.

class

FakeKeyStore

Ensamblado: EricksonLopez.Security.Testing
public sealed class FakeKeyStore : IKeyStore
Implementa: IKeyStore

Provides an in-memory test double implementation of `IKeyStore` with inspectable state and simulated failure injection.

Miembros (7)

  • methodGetKeyAsync
    public ValueTask<Result<CryptographicKey>> GetKeyAsync(KeyIdentifier keyId, KeyVersion version, CancellationToken cancellationToken = default)

    Retrieves a cryptographic key by identifier and version.

    keyId: KeyIdentifier
    The key identifier.
    version: KeyVersion
    The key version.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the `CryptographicKey`.

  • methodListMetadataAsync
    public ValueTask<Result<IReadOnlyList<KeyMetadata>>> ListMetadataAsync(KeyPurpose? purpose = null, CancellationToken cancellationToken = default)

    Retrieves all key metadata stored in the repository.

    purpose: KeyPurpose?
    Optional purpose filter.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a result with a list of key metadata records.

  • methodReset
    public void Reset()

    Resets all stored keys and clears injected errors.

  • methodSaveKeyAsync
    public ValueTask<Result> SaveKeyAsync(CryptographicKey key, CancellationToken cancellationToken = default)

    Persists a new cryptographic key into the key store.

    key: CryptographicKey
    The cryptographic key to save.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating success or failure.

  • methodUpdateStatusAsync
    public ValueTask<Result> UpdateStatusAsync(KeyIdentifier keyId, KeyVersion version, KeyStatus newStatus, CancellationToken cancellationToken = default)

    Updates the lifecycle status of a specific key.

    keyId: KeyIdentifier
    The key identifier.
    version: KeyVersion
    The key version.
    newStatus: KeyStatus
    The new lifecycle status.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating the outcome.

  • propertyCount
    public int Count { get; }

    Gets the number of keys currently stored.

  • propertyInjectedError
    public Error? InjectedError { get; set; }

    Gets or sets an optional simulated error to return on all operations.

class

FakePasswordHasher

Ensamblado: EricksonLopez.Security.Testing
public sealed class FakePasswordHasher : IPasswordHasher
Implementa: IPasswordHasher

Provides a deterministic test double implementation of `IPasswordHasher` designed for high-speed unit testing without computational PBKDF2/Argon2 hashing overhead.

Miembros (5)

  • methodHashPassword
    public string HashPassword(ReadOnlySpan<char> password)

    Computes a cryptographically salted and parameterized password hash for the specified password.

    password: ReadOnlySpan<char>
    The plaintext password character span. Must not exceed 256 characters.

    Retorna: A standardized, self-describing password hash string.

    Exceptions: ArgumentOutOfRangeException: `password` length exceeds 256 characters

  • methodNeedsRehash
    public bool NeedsRehash(string hashedPassword)

    Determines whether the given stored password hash requires rehashing due to parameter updates or algorithm evolution.

    hashedPassword: string
    The stored hash string to evaluate

    Retorna: `true` if the hash should be regenerated with current parameters; otherwise, `false`.

  • methodVerifyPassword
    public PasswordVerificationResult VerifyPassword(ReadOnlySpan<char> password, string hashedPassword)

    Verifies a plaintext password against a stored hashed password using constant-time evaluation.

    password: ReadOnlySpan<char>
    The candidate password character span to verify
    hashedPassword: string
    The stored hashed password string to evaluate

    Retorna: A `PasswordVerificationResult` indicating success, success with rehash required, or failure.

  • propertyAlgorithm
    public PasswordHashAlgorithm Algorithm { get; }

    Gets the simulated password hash algorithm.

  • propertySimulateNeedsRehash
    public bool SimulateNeedsRehash { get; set; }

    Gets or sets a value indicating whether `NeedsRehash` should return `true`.

class

FakeSecretProtector

Ensamblado: EricksonLopez.Security.Testing
public sealed class FakeSecretProtector : ISecretProtector
Implementa: ISecretProtector

Provides an in-memory test double implementation of `ISecretProtector` using simple XOR masking for fast unit testing.

Miembros (6)

  • methodProtect
    public Result<byte[]> Protect(ReadOnlySpan<byte> secret, KeyPurpose purpose = KeyPurpose.SecretProtection, AuthenticatedContext expectedAssociatedData = default)

    Encrypts and authenticates a plaintext secret span into a newly allocated protected payload.

    secret: ReadOnlySpan<byte>
    Plaintext secret byte span.
    purpose: KeyPurpose
    Cryptographic key purpose for encryption (defaults to `KeyPurpose.SecretProtection`).
    expectedAssociatedData: AuthenticatedContext
    Optional authenticated associated data bound to the envelope.

    Retorna: A `Result<T>` containing the serialized protected binary envelope on success.

  • methodProtectAsync
    public ValueTask<Result<byte[]>> ProtectAsync(ReadOnlyMemory<byte> secret, KeyPurpose purpose = KeyPurpose.SecretProtection, AuthenticatedContext expectedAssociatedData = default, CancellationToken cancellationToken = default)

    Encrypts and authenticates a secret byte buffer into a protected cryptographic envelope payload.

    secret: ReadOnlyMemory<byte>
    Plaintext secret memory.
    purpose: KeyPurpose
    Cryptographic key purpose (defaults to `KeyPurpose.SecretProtection`).
    expectedAssociatedData: AuthenticatedContext
    Optional authenticated associated data.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the serialized protected binary envelope on success.

  • methodUnprotect
    public Result<byte[]> Unprotect(ReadOnlySpan<byte> protectedData, AuthenticatedContext expectedAssociatedData = default)

    Decrypts and authenticates a protected envelope span back into plaintext secret bytes.

    protectedData: ReadOnlySpan<byte>
    Protected binary envelope byte span.
    expectedAssociatedData: AuthenticatedContext
    Optional authenticated associated data to verify against the envelope.

    Retorna: A `Result<T>` containing the decrypted plaintext byte array on success.

  • methodUnprotectAsync
    public ValueTask<Result<byte[]>> UnprotectAsync(ReadOnlyMemory<byte> protectedData, AuthenticatedContext expectedAssociatedData = default, CancellationToken cancellationToken = default)

    Decrypts and authenticates a protected cryptographic envelope payload back into plaintext secret bytes.

    protectedData: ReadOnlyMemory<byte>
    Protected binary envelope memory.
    expectedAssociatedData: AuthenticatedContext
    Optional authenticated associated data to verify.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the decrypted plaintext byte array on success.

  • methodUnprotectToSecretBufferAsync
    public ValueTask<Result<ISecretBuffer>> UnprotectToSecretBufferAsync(ReadOnlyMemory<byte> protectedData, AuthenticatedContext expectedAssociatedData = default, CancellationToken cancellationToken = default)

    Decrypts and authenticates a protected cryptographic envelope payload into an unmanaged secret buffer whose memory is zeroized upon disposal.

    protectedData: ReadOnlyMemory<byte>
    Protected binary envelope memory.
    expectedAssociatedData: AuthenticatedContext
    Optional authenticated associated data to verify.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the decrypted `ISecretBuffer` on success.

  • propertyInjectedError
    public Error? InjectedError { get; set; }

    Gets or sets an optional simulated error to return on protect/unprotect operations.

class

FakeSecretStore

Ensamblado: EricksonLopez.Security.Testing
public sealed class FakeSecretStore : ISecretStore
Implementa: ISecretStore

Provides an in-memory test double implementation of `ISecretStore` with inspectable state and simulated failure injection.

Miembros (5)

  • methodGetSecretAsync
    public ValueTask<Result<Redacted<string>>> GetSecretAsync(string secretName, CancellationToken cancellationToken = default)

    Retrieves a secret by name as a memory-safe `Redacted<T>` string container.

    secretName: string
    The unique secret key name.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` containing the secret value.

  • methodReset
    public void Reset()

    Resets all stored secrets and clears injected errors.

  • methodSetSecretAsync
    public ValueTask<Result> SetSecretAsync(string secretName, string secretValue, CancellationToken cancellationToken = default)

    Sets or updates a secret in the underlying store.

    secretName: string
    The unique secret key name.
    secretValue: string
    The secret value to persist.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating success or failure.

  • propertyCount
    public int Count { get; }

    Gets the number of secrets currently stored.

  • propertyInjectedError
    public Error? InjectedError { get; set; }

    Gets or sets an optional simulated error to return on all operations.

EricksonLopez.Security.Testing.Http#

1
class

TestHttpMessageHandler

Ensamblado: EricksonLopez.Security.Testing
public sealed class TestHttpMessageHandler : HttpMessageHandler
Hereda de: HttpMessageHandler

Provides a configurable test double implementation of `HttpMessageHandler` for deterministic HTTP testing.

Miembros (9)

  • constructorTestHttpMessageHandler
    public TestHttpMessageHandler(Exception exceptionToThrow)

    Initializes a new instance of the `TestHttpMessageHandler` class that throws a specified exception when invoked.

    exceptionToThrow: Exception
    The exception to throw on send.

    Exceptions: ArgumentNullException: `exceptionToThrow` is `null`

  • constructorTestHttpMessageHandler
    public TestHttpMessageHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> asyncHandler)

    Initializes a new instance of the `TestHttpMessageHandler` class with an asynchronous handler delegate.

    asyncHandler: Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>>
    The delegate invoked on each request.

    Exceptions: ArgumentNullException: `asyncHandler` is `null`

  • constructorTestHttpMessageHandler
    public TestHttpMessageHandler(Func<HttpRequestMessage, HttpResponseMessage> syncHandler)

    Initializes a new instance of the `TestHttpMessageHandler` class with a synchronous handler delegate.

    syncHandler: Func<HttpRequestMessage, HttpResponseMessage>
    The delegate invoked on each request.

    Exceptions: ArgumentNullException: `syncHandler` is `null`

  • constructorTestHttpMessageHandler
    public TestHttpMessageHandler(string responseContent, HttpStatusCode statusCode = HttpStatusCode.OK, string mediaType = "")

    Initializes a new instance of the `TestHttpMessageHandler` class returning a constant string response and status code.

    responseContent: string
    The string content to return.
    statusCode: HttpStatusCode
    The HTTP status code (defaults to OK).
    mediaType: string
    The media type for the response content (defaults to "text/plain").
  • propertyIsDisposed
    public bool IsDisposed { get; private set; }

    Gets a value indicating whether this handler has been disposed.

  • propertyLastRequest
    public HttpRequestMessage? LastRequest { get; private set; }

    Gets the most recent request sent through this handler, if any.

  • propertyLastRequestHeaders
    public HttpRequestHeaders? LastRequestHeaders { get; }

    Gets the headers from the most recent request sent through this handler, if any.

  • propertyRequestCount
    public int RequestCount { get; }

    Gets the total number of requests handled.

  • propertyRequests
    public IReadOnlyCollection<HttpRequestMessage> Requests { get; }

    Gets the collection of all requests received by this handler.

EricksonLopez.Security.Testing.Logging#

2
record

FakeLogRecord

Ensamblado: EricksonLopez.Security.Testing
public sealed record FakeLogRecord(LogLevel LogLevel, EventId EventId, object? State, Exception? Exception, string Message)

Represents an immutable record of a captured log invocation in `FakeLogger<T>`.

Miembros (6)

  • constructorFakeLogRecord
    public FakeLogRecord(LogLevel LogLevel, EventId EventId, object? State, Exception? Exception, string Message)

    Initializes a new instance of FakeLogRecord.

    LogLevel: LogLevel
    The severity level of the log entry.
    EventId: EventId
    The event identifier associated with the log entry.
    State: object?
    The state object passed to the logger.
    Exception: Exception?
    The exception associated with the log entry, if any.
    Message: string
    The formatted log message text.
  • propertyEventId
    public EventId EventId { get; init; }

    The event identifier associated with the log entry.

  • propertyException
    public Exception? Exception { get; init; }

    The exception associated with the log entry, if any.

  • propertyLogLevel
    public LogLevel LogLevel { get; init; }

    The severity level of the log entry.

  • propertyMessage
    public string Message { get; init; }

    The formatted log message text.

  • propertyState
    public object? State { get; init; }

    The state object passed to the logger.

class

FakeLogger<TCategoryName>

Ensamblado: EricksonLopez.Security.Testing
public sealed class FakeLogger<TCategoryName> : ILogger<TCategoryName>
Implementa: ILogger<TCategoryName>

Provides a thread-safe test double implementation of `ILogger<TCategoryName>` for capturing and asserting on structured log output.

Notas:

Type parameters: TCategoryName: The logger category type.

Miembros (12)

  • constructorFakeLogger
    public FakeLogger(LogLevel minLevel = LogLevel.Trace)

    Initializes a new instance of the `FakeLogger<TCategoryName>` class with an optional minimum enabled log level.

    minLevel: LogLevel
    The minimum log level to accept (defaults to `LogLevel.Trace`).
  • methodBeginScope<TState>
    public IDisposable? BeginScope<TState>(TState state) where TState : notnull

    Inherits documentation from base type or interface.

    state: TState
  • methodClear
    public void Clear()

    Clears all recorded entries.

  • methodHasError
    public bool HasError(string substring)

    Determines whether an error log entry contains the specified substring.

    substring: string
    The substring to look for in error log messages.

    Retorna: `true` if a matching error entry was logged; otherwise, `false`.

  • methodHasMessage
    public bool HasMessage(LogLevel level, string substring)

    Determines whether any captured log entry with the given log level contains the specified substring.

    level: LogLevel
    The expected log level.
    substring: string
    The substring to look for.

    Retorna: `true` if a matching entry was logged; otherwise, `false`.

    Exceptions: ArgumentNullException: `substring` is `null`

  • methodHasMessage
    public bool HasMessage(string substring)

    Determines whether any captured log entry contains the specified substring.

    substring: string
    The substring to look for.

    Retorna: `true` if a matching entry was logged; otherwise, `false`.

    Exceptions: ArgumentNullException: `substring` is `null`

  • methodHasWarning
    public bool HasWarning(string substring)

    Determines whether a warning log entry contains the specified substring.

    substring: string
    The substring to look for in warning log messages.

    Retorna: `true` if a matching warning entry was logged; otherwise, `false`.

  • methodIsEnabled
    public bool IsEnabled(LogLevel logLevel)

    Inherits documentation from base type or interface.

    logLevel: LogLevel
  • methodLog<TState>
    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)

    Inherits documentation from base type or interface.

    logLevel: LogLevel
    eventId: EventId
    state: TState
    exception: Exception?
    formatter: Func<TState, Exception?, string>
  • propertyCount
    public int Count { get; }

    Gets the total number of captured log entries.

  • propertyEntries
    public IReadOnlyList<FakeLogRecord> Entries { get; }

    Gets a snapshot of all captured log entries in chronological order.

  • propertyMessages
    public IReadOnlyList<string> Messages { get; }

    Gets a list of all formatted log message strings captured so far.

EricksonLopez.Security.Tokens#

9
class

ApiKeyGenerator

Ensamblado: EricksonLopez.Security
public sealed class ApiKeyGenerator : IApiKeyGenerator
Implementa: IApiKeyGenerator

Provides a generator implementation for issuing structured, cryptographically high-entropy API keys. Formats keys as: `{prefix}_{idHex16}_{secretUrlSafe}`. Persists only the hashed secret while returning the full plaintext key once upon issuance.

Miembros (3)

  • constructorApiKeyGenerator
    public ApiKeyGenerator(ITokenHasher tokenHasher)

    Initializes a new instance of the `ApiKeyGenerator` class with a specified token hasher.

    tokenHasher: ITokenHasher
    The token hasher used to hash issued API key secrets.

    Exceptions: ArgumentNullException: `tokenHasher` is `null`

  • methodGenerateApiKey
    public ApiKeyIssuanceResult GenerateApiKey(string ownerId, string name, string prefix = "", TimeSpan? lifetime = null, IReadOnlySet<string>? scopes = null)

    Generates a new structured API key with the specified metadata and constraints.

    ownerId: string
    The identifier of the owning entity or tenant
    name: string
    The descriptive name for the API key
    prefix: string
    The display prefix to prepend to the key
    lifetime: TimeSpan?
    The optional lifetime validity period
    scopes: IReadOnlySet<string>?
    The optional set of authorized scopes

    Retorna: An `ApiKeyIssuanceResult` containing the created API key entity and the plaintext key.

    Memory Note (APIKEY-05): The `ApiKeyIssuanceResult.PlaintextApiKey` property of the returned result is a managed `string` and cannot be explicitly zeroed. The plaintext API key will remain in the managed heap until garbage collected. If your security policy requires that the plaintext key be zeroed immediately after transmission to the client, use `GenerateApiKeySecretBuffer` instead, which returns the plaintext key in a `Memory.SecretBuffer` that is explicitly zeroed when disposed.

  • methodGenerateApiKeySecretBuffer
    public (ApiKey Key, Memory.SecretBuffer SecretBuffer) GenerateApiKeySecretBuffer(string ownerId, string name, string prefix = "", TimeSpan? lifetime = null, IReadOnlySet<string>? scopes = null)

    Issues a new structured API key and returns the full plaintext secret wrapped inside a zeroizable `Memory.SecretBuffer`, preventing long-term retention of sensitive credentials in the managed garbage collection heap.

    ownerId: string
    The owner or tenant identifier.
    name: string
    The human-readable key name.
    prefix: string
    The key prefix.
    lifetime: TimeSpan?
    Optional key lifetime.
    scopes: IReadOnlySet<string>?
    Optional authorized scopes.

    Retorna: A tuple containing the persisted `ApiKey` descriptor and the zeroizable `Memory.SecretBuffer` containing the UTF-8 plaintext key bytes.

class

ApiKeyValidator

Ensamblado: EricksonLopez.Security
public sealed class ApiKeyValidator : IApiKeyValidator
Implementa: IApiKeyValidator

Provides an implementation of `IApiKeyValidator` to authenticate incoming API keys using constant-time evaluation, repository lookups, and lifecycle status validation.

Miembros (2)

  • constructorApiKeyValidator
    public ApiKeyValidator(IApiKeyStore apiKeyStore, ITokenHasher? tokenHasher = null)

    Initializes a new instance of the `ApiKeyValidator` class.

    apiKeyStore: IApiKeyStore
    The API key storage repository.
    tokenHasher: ITokenHasher?
    The optional custom token hasher (defaults to secure keyed HMAC-SHA256 with an application-level pepper).

    Exceptions: ArgumentNullException: `apiKeyStore` is `null`

  • methodValidateApiKeyAsync
    public async ValueTask<Result<ApiKey>> ValidateApiKeyAsync(string plaintextApiKey, CancellationToken cancellationToken = default)

    Validates an incoming plaintext API key against the registered API key store.

    plaintextApiKey: string
    The presented plaintext API key string to validate
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` with the validated `ApiKey` on success, or a failure error.

class

ConcurrentTokenRefreshHttpHandler

Ensamblado: EricksonLopez.Security
public sealed class ConcurrentTokenRefreshHttpHandler : DelegatingHandler
Hereda de: DelegatingHandler

Outbound HTTP `DelegatingHandler` that coalesces concurrent `401 Unauthorized` bearer token refreshes into a single flight using an asynchronous mutex and double-checked token comparison, preventing RFC 9700 refresh-token reuse lockouts.

Miembros (1)

  • constructorConcurrentTokenRefreshHttpHandler
    public ConcurrentTokenRefreshHttpHandler(Func<CancellationToken, ValueTask<string?>> getAccessTokenAsync, Func<CancellationToken, ValueTask<bool>> refreshTokensAsync)

    Initializes a new instance of the `ConcurrentTokenRefreshHttpHandler` class.

    getAccessTokenAsync: Func<CancellationToken, ValueTask<string?>>
    Delegate returning the current cached bearer access token.
    refreshTokensAsync: Func<CancellationToken, ValueTask<bool>>
    Delegate performing the token rotation and returning `true` when refreshed.

    Exceptions: ArgumentNullException: `getAccessTokenAsync` or `refreshTokensAsync` is `null`.

class

HmacSha256TokenHasher

Ensamblado: EricksonLopez.Security
public sealed class HmacSha256TokenHasher : ITokenHasher, IDisposable
Implementa: IDisposable, ITokenHasher

Provides a token hasher implementation using HMAC-SHA256 (or keyed SHA-256) to produce secure, deterministic hash digests for database token lookup without storing reversible token plaintext.

Miembros (6)

  • constructorHmacSha256TokenHasher
    public HmacSha256TokenHasher(ReadOnlySpan<byte> pepperKey)

    Initializes a new instance of the `HmacSha256TokenHasher` class with an HMAC pepper key.

    pepperKey: ReadOnlySpan<byte>
    The secret pepper key bytes (must be at least 32 bytes / 256 bits).

    Exceptions: ArgumentOutOfRangeException: `pepperKey` is less than 32 bytes

  • methodDispose
    public void Dispose()

    Releases the resources used by this instance and actively zeroes the pepper key bytes from memory.

  • methodHashToken
    public string HashToken(ReadOnlySpan<char> token)

    Computes a deterministic cryptographic hash of the token suitable for indexed database lookups.

    token: ReadOnlySpan<char>
    The token character span to hash

    Retorna: A hex-encoded or base64-encoded hash digest of the token.

    Memory Note (HMAC-06): The returned `string` is a managed heap allocation containing the hex-encoded HMAC-SHA256 hash. .NET strings are immutable and cannot be explicitly zeroed — the hash value will remain in memory until the next garbage collection cycle. For callers operating in a hot path or that need to minimize the window during which the hash is accessible in memory, prefer `TryHashToken(ReadOnlySpan<char>, Span<char>, out int)`, which writes directly into a caller-provided `Span<T>` that can be zeroed after use.

  • methodTryHashToken
    public bool TryHashToken(ReadOnlySpan<char> token, Span<char> destination, out int charsWritten)

    Computes the cryptographic hash of a token into a destination character span without heap allocations.

    token: ReadOnlySpan<char>
    The token character span to hash.
    destination: Span<char>
    The destination buffer which must be at least 64 characters in length.
    charsWritten: out int
    When this method returns, the number of characters written to `destination`.

    Retorna: `true` if the hash was successfully written; otherwise, `false`.

  • methodVerifyToken
    public bool VerifyToken(ReadOnlySpan<char> token, string expectedHash)

    Verifies a candidate token against an expected hash using constant-time evaluation.

    token: ReadOnlySpan<char>
    The candidate token character span to verify
    expectedHash: string
    The expected token hash to compare against

    Retorna: `true` if the candidate token matches the expected hash; otherwise, `false`.

  • propertyIsDisposed
    public bool IsDisposed { get; }

    Gets a value indicating whether this instance has been disposed.

class

InMemoryApiKeyStore

Ensamblado: EricksonLopez.Security
public sealed class InMemoryApiKeyStore : IApiKeyStore
Implementa: IApiKeyStore

Provides a thread-safe in-memory API key store implementation of `IApiKeyStore` suitable for testing, development, and containerized microservice deployments.

Miembros (4)

  • constructorInMemoryApiKeyStore
    public InMemoryApiKeyStore()

    Initializes a new instance of the `InMemoryApiKeyStore` class.

  • methodGetByIdAsync
    public ValueTask<Result<ApiKey>> GetByIdAsync(ApiKeyId keyId, CancellationToken cancellationToken = default)

    Retrieves an API key entity by its lookup identifier.

    keyId: ApiKeyId
    The unique lookup identifier of the API key
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result<T>` with the matching `ApiKey`, or a not-found error.

  • methodRevokeAsync
    public ValueTask<Result> RevokeAsync(ApiKeyId keyId, CancellationToken cancellationToken = default)

    Revokes an existing API key.

    keyId: ApiKeyId
    The unique lookup identifier of the API key to revoke
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating whether the operation succeeded.

  • methodSaveAsync
    public ValueTask<Result> SaveAsync(ApiKey apiKey, CancellationToken cancellationToken = default)

    Persists a newly issued API key entity.

    apiKey: ApiKey
    The API key entity to persist
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A value task representing the asynchronous operation. The task result contains a `Result` indicating whether the operation succeeded.

class

OpaqueTokenGenerator

Ensamblado: EricksonLopez.Security
public sealed class OpaqueTokenGenerator : ITokenGenerator
Implementa: ITokenGenerator

Provides an implementation of `ITokenGenerator` generating cryptographically strong opaque security tokens, session identifiers, and verification codes.

Miembros (8)

  • constructorOpaqueTokenGenerator
    public OpaqueTokenGenerator()

    Initializes a new instance of the `OpaqueTokenGenerator` class.

  • methodGenerateHexToken
    public string GenerateHexToken(int byteLength = 32)

    Generates a cryptographically secure hex-encoded token string.

    byteLength: int
    The number of random bytes to generate, defaulting to 32 bytes

    Retorna: A lowercase hex-encoded token string.

  • methodGenerateNumericCode
    public string GenerateNumericCode(int digits = 6)

    Generates a cryptographically secure numeric code of the specified digit length.

    digits: int
    The number of digits in the generated code, defaulting to 6

    Retorna: A numeric code string of the specified length.

  • methodGenerateToken
    public OpaqueToken GenerateToken(int byteLength = 32)

    Generates a cryptographically secure opaque token with the specified entropy byte length.

    byteLength: int
    The number of random bytes to generate, defaulting to 32 bytes

    Retorna: A new `OpaqueToken` containing the generated random bytes.

  • methodGenerateTokenSecretBuffer
    public ISecretBuffer GenerateTokenSecretBuffer(int byteLength = 32)

    Generates a cryptographically secure token and stores its raw bytes in a zeroizable secret buffer.

    byteLength: int
    The number of random bytes to generate, defaulting to 32 bytes.

    Retorna: A zeroizable `ISecretBuffer` containing the generated random bytes.

  • methodGenerateUrlSafeToken
    public string GenerateUrlSafeToken(int byteLength = 32)

    Generates a cryptographically secure URL-safe base64-encoded token string.

    byteLength: int
    The number of random bytes to generate, defaulting to 32 bytes

    Retorna: A URL-safe token string.

  • methodTryGenerateUrlSafeToken
    public bool TryGenerateUrlSafeToken(Span<char> destination, int byteLength, out int charsWritten)

    Attempts to generate a cryptographically secure URL-safe token into the specified destination span.

    destination: Span<char>
    The destination span for the generated token characters.
    byteLength: int
    The number of random bytes to generate, defaulting to 32 bytes.
    charsWritten: out int
    The number of characters written to the destination span.

    Retorna: `true` if the token was successfully generated; otherwise, `false`.

  • fieldShared
    public static readonly OpaqueTokenGenerator Shared

    Gets the shared singleton instance of `OpaqueTokenGenerator`.

class

ServiceCredentialEvaluator

Ensamblado: EricksonLopez.Security
public sealed class ServiceCredentialEvaluator : IServiceCredentialEvaluator
Implementa: IServiceCredentialEvaluator

Evaluates incoming M2M service API keys in constant time against persisted `ServiceCredentialRecord` metadata, enforcing versioned HMAC proof-of-possession first (defeating existence and status timing oracles), followed by revocation, absolute expiration, rotation grace-window (`GraceUntilUtc`), and CIDR network allowlist checks.

Miembros (3)

  • constructorServiceCredentialEvaluator
    public ServiceCredentialEvaluator(IVersionedCredentialHmacService hmacService, TimeProvider? timeProvider = null)

    Initializes a new instance of the `ServiceCredentialEvaluator` class.

    hmacService: IVersionedCredentialHmacService
    The versioned credential HMAC service.
    timeProvider: TimeProvider?
    Optional time provider (defaults to `TimeProvider.System`).

    Exceptions: ArgumentNullException: `hmacService` is `null`.

  • methodEvaluate
    public Result<ServiceCredentialRecord> Evaluate(ReadOnlySpan<char> rawApiKey, ServiceCredentialRecord? candidate, string? clientIpAddress = null)

    Evaluates a presented service API key against a candidate `ServiceCredentialRecord` (or `null` on store miss) with timing-equalized HMAC verification, revocation, expiration, rotation grace-window, and CIDR allowlist checks.

    rawApiKey: ReadOnlySpan<char>
    The raw service API key presented by the caller.
    candidate: ServiceCredentialRecord?
    The stored credential record resolved by prefix, or `null` when not found.
    clientIpAddress: string?
    Optional client IP address string evaluated when `ServiceCredentialRecord.AllowedCidrs` is non-empty.

    Retorna: A `Result<T>` containing the verified `ServiceCredentialRecord` on success, or a typed security error.

  • methodTryExtractKeyPrefix
    public bool TryExtractKeyPrefix(ReadOnlySpan<char> rawApiKey, out string keyPrefix)

    Attempts to extract the indexed `{prefixTag}_{randomId8}` lookup prefix from a raw service API key.

    rawApiKey: ReadOnlySpan<char>
    The presented raw service API key.
    keyPrefix: out string
    When this method returns, contains the extracted key prefix if valid.

    Retorna: `true` if the credential matches the canonical structural format; otherwise, `false`.

class

VersionedCredentialHmacOptions

Ensamblado: EricksonLopez.Security
public sealed class VersionedCredentialHmacOptions

Configures versioned server HMAC pepper keys and HKDF domain separation for `VersionedCredentialHmacService`.

Miembros (4)

  • methodAddPepperKeyFromEncoded
    public VersionedCredentialHmacOptions AddPepperKeyFromEncoded(int version, string encodedPepper)

    Decodes and registers a server HMAC pepper key for `version` from Base64 or UTF-8 material (minimum 32 bytes).

    version: int
    The positive pepper key version (`>= 1`).
    encodedPepper: string
    The Base64 or high-entropy UTF-8 pepper material.

    Retorna: This `VersionedCredentialHmacOptions` instance for fluent configuration.

    Exceptions: ArgumentOutOfRangeException: `version` is less than 1.; ArgumentException: `encodedPepper` is null, whitespace, or contains fewer than 32 bytes.

  • propertyActivePepperVersion
    public int? ActivePepperVersion { get; set; }

    Gets or sets the active pepper version used when issuing or hashing new credentials. When `null`, the highest registered version in `PepperKeys` is selected automatically.

  • propertyHkdfDomainPrefix
    public string HkdfDomainPrefix { get; set; }

    Gets or sets the HKDF `info` domain-separation prefix (`{HkdfDomainPrefix}:{domainPurpose}`). Defaults to `"ericksonlopez.hmac.v1"`.

  • propertyPepperKeys
    public IDictionary<int, byte[]> PepperKeys { get; }

    Gets the versioned server pepper keys (minimum 32 bytes each) indexed by positive version (`>= 1`).

class

VersionedCredentialHmacService

Ensamblado: EricksonLopez.Security
public sealed class VersionedCredentialHmacService : IVersionedCredentialHmacService, IDisposable
Implementa: IDisposable, IVersionedCredentialHmacService

Provides versioned, domain-separated HKDF-SHA256 + HMAC-SHA256 hashing, constant-time verification, single-use `XXXX-XXXX-XXXX` emergency backup code generation, and structured M2M service API key issuance.

Miembros (12)

  • constructorVersionedCredentialHmacService
    public VersionedCredentialHmacService(IOptions<VersionedCredentialHmacOptions> options)

    Initializes a new instance of the `VersionedCredentialHmacService` class from `IOptions<TOptions>`.

    options: IOptions<VersionedCredentialHmacOptions>
    The configured `VersionedCredentialHmacOptions` wrapper.

    Exceptions: ArgumentNullException: `options` is `null`.

  • constructorVersionedCredentialHmacService
    public VersionedCredentialHmacService(VersionedCredentialHmacOptions options)

    Initializes a new instance of the `VersionedCredentialHmacService` class.

    options: VersionedCredentialHmacOptions
    The configured `VersionedCredentialHmacOptions`.

    Exceptions: ArgumentNullException: `options` is `null`.; ArgumentException: Options contain invalid versions, short keys, missing active version, or empty domain prefix.

  • methodComputeBackupCodeHmac
    public string ComputeBackupCodeHmac(ReadOnlySpan<char> rawBackupCode, int? pepperVersion = null)

    Computes the domain-separated 64-character lowercase hexadecimal HMAC-SHA256 digest of a backup code after stripping formatting delimiters and normalizing to uppercase alphanumeric characters.

    rawBackupCode: ReadOnlySpan<char>
    The raw user-supplied backup code.
    pepperVersion: int?
    Optional pepper version (`null` uses `ActivePepperVersion`).

    Retorna: A 64-character lowercase hexadecimal HMAC-SHA256 digest.

  • methodComputeHmac
    public string ComputeHmac(string domainPurpose, ReadOnlySpan<char> credential, int? pepperVersion = null)

    Computes a domain-separated 64-character lowercase hexadecimal HMAC-SHA256 digest for a high-entropy credential.

    domainPurpose: string
    The non-empty domain purpose label (for example, `"service-credential"` or `"refresh-token"`).
    credential: ReadOnlySpan<char>
    The raw credential characters.
    pepperVersion: int?
    Optional pepper version (`null` uses `ActivePepperVersion`).

    Retorna: A 64-character lowercase hexadecimal HMAC-SHA256 digest, or 64 zeros if `credential` is empty or whitespace.

  • methodComputeServiceCredentialHmac
    public string ComputeServiceCredentialHmac(ReadOnlySpan<char> rawApiKey, int? pepperVersion = null)

    Computes the domain-separated HMAC-SHA256 digest of a full service API key for indexed lookup or verification.

    rawApiKey: ReadOnlySpan<char>
    The raw service API key.
    pepperVersion: int?
    Optional pepper version (`null` uses `ActivePepperVersion`).

    Retorna: A 64-character lowercase hexadecimal HMAC-SHA256 digest.

  • methodDispose
    public void Dispose()

    Scrubs all server pepper keys from memory.

  • methodGenerateBackupCodes
    public IReadOnlyList<GeneratedBackupCode> GenerateBackupCodes(int count = 8)

    Generates a set of unique, unambiguous single-use emergency backup codes formatted as `XXXX-XXXX-XXXX` paired with their normalized domain-separated HMAC-SHA256 digests.

    count: int
    The number of unique backup codes to generate (default 8).

    Retorna: An immutable list of `GeneratedBackupCode` entries.

  • methodIssueServiceCredential
    public IssuedServiceCredential IssueServiceCredential(string prefixTag = "")

    Issues a structured M2M service API key (`{prefixTag}_{randomId8}_{base64UrlSecret}`) with 256 bits of CSPRNG entropy, scrubbing the raw secret byte buffer before returning.

    prefixTag: string
    The environment-qualified key prefix tag (for example, `"sk_live"` or `"sk_test"`).

    Retorna: An `IssuedServiceCredential` containing the one-time plaintext key, lookup prefix, HMAC digest, and pepper version.

  • methodVerifyBackupCode
    public bool VerifyBackupCode(ReadOnlySpan<char> rawBackupCode, ReadOnlySpan<char> expectedHexDigest, int? pepperVersion = null)

    Verifies a user-supplied backup code against a stored 64-character hexadecimal HMAC-SHA256 digest in constant time.

    rawBackupCode: ReadOnlySpan<char>
    The raw user-supplied backup code.
    expectedHexDigest: ReadOnlySpan<char>
    The stored 64-character hexadecimal HMAC-SHA256 digest.
    pepperVersion: int?
    Optional pepper version stored alongside the backup code.

    Retorna: `true` if the normalized backup code matches `expectedHexDigest`; otherwise, `false`.

  • methodVerifyHmac
    public bool VerifyHmac(string domainPurpose, ReadOnlySpan<char> credential, ReadOnlySpan<char> expectedHexDigest, int? pepperVersion = null)

    Verifies a raw credential against an expected 64-character hexadecimal HMAC-SHA256 digest in constant time.

    domainPurpose: string
    The non-empty domain purpose label.
    credential: ReadOnlySpan<char>
    The raw credential characters presented by the caller.
    expectedHexDigest: ReadOnlySpan<char>
    The stored 64-character hexadecimal HMAC-SHA256 digest.
    pepperVersion: int?
    Optional pepper version stored alongside the credential.

    Retorna: `true` if the credential matches `expectedHexDigest`; otherwise, `false`.

  • propertyActivePepperVersion
    public int ActivePepperVersion { get; }

    Gets the currently active server pepper version used when issuing or hashing new credentials.

  • propertyIsDisposed
    public bool IsDisposed { get; }

    Gets a value indicating whether this instance has been disposed.

EricksonLopez.Security.WebAuthn.Fido2.Abstractions#

5
interface

IAttestationTrustStore

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public interface IAttestationTrustStore

Provides trusted root certificates for verifying WebAuthn attestation statement certificate chains.

Miembros (1)

  • methodGetTrustAnchors
    IReadOnlyList<X509Certificate2> GetTrustAnchors(string format, Guid? aaguid)

    Gets the trusted root certificates for the specified attestation format and optional AAGUID.

    format: string
    The attestation statement format (e.g. "packed", "fido-u2f", "android-safetynet", "tpm").
    aaguid: Guid?
    The optional Authenticator Attestation GUID (AAGUID).

    Retorna: A collection of trusted root certificates, or empty if none are known.

interface

IAttestationVerifier

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public interface IAttestationVerifier

Defines the contract for verifying a specific WebAuthn attestation statement format.

Miembros (2)

  • methodVerify
    Result Verify(AttestationStatement statement, AuthenticatorData authData, byte[] clientDataHash)

    Verifies the attestation statement against the authenticator data and client data hash.

    statement: AttestationStatement
    The parsed attestation statement.
    authData: AuthenticatorData
    The parsed authenticator data.
    clientDataHash: byte[]
    The SHA-256 hash of clientDataJSON.

    Retorna: A result indicating success or a verification error.

  • propertyFormat
    string Format { get; }

    Gets the format string handled by this verifier (e.g. "none", "packed", "fido-u2f").

interface

IAuthenticatorDataParser

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public interface IAuthenticatorDataParser

Defines the contract for parsing binary Authenticator Data byte sequences.

Miembros (1)

  • methodParse
    Result<AuthenticatorData> Parse(ReadOnlySpan<byte> authDataBytes)

    Parses an Authenticator Data structure from a byte span.

    authDataBytes: ReadOnlySpan<byte>
    The binary authenticatorData span.

    Retorna: A result containing the parsed `AuthenticatorData` or an error.

interface

ICoseKeyParser

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public interface ICoseKeyParser

Defines the contract for parsing binary CBOR-encoded COSE keys into `CosePublicKey` models.

Miembros (1)

  • methodParse
    Result<CosePublicKey> Parse(ReadOnlySpan<byte> cborBytes)

    Parses a CBOR-encoded COSE Key map from a byte span.

    cborBytes: ReadOnlySpan<byte>
    The raw CBOR byte span.

    Retorna: A result containing the parsed `CosePublicKey` or an error.

interface

IWebAuthnCeremonyService

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public interface IWebAuthnCeremonyService

Defines the contract for orchestrating WebAuthn Level 2/3 registration and authentication ceremonies.

Miembros (4)

  • methodCreateAuthenticationOptions
    CredentialRequestOptions CreateAuthenticationOptions(CredentialRequestOptions? customOptions = null)

    Generates the options payload required to initiate a credential assertion (authentication) ceremony.

    customOptions: CredentialRequestOptions?
    Optional overrides for default options.

    Retorna: A new `CredentialRequestOptions` instance containing a fresh cryptographic challenge.

  • methodCreateRegistrationOptions
    CredentialCreateOptions CreateRegistrationOptions(PublicKeyCredentialUserEntity user, CredentialCreateOptions? customOptions = null)

    Generates the options payload required to initiate a credential creation ceremony.

    user: PublicKeyCredentialUserEntity
    The user entity creating the credential.
    customOptions: CredentialCreateOptions?
    Optional overrides for default options.

    Retorna: A new `CredentialCreateOptions` instance containing a fresh cryptographic challenge.

  • methodVerifyAuthenticationAsync
    Task<Result<VerifiedCredentialAssertion>> VerifyAuthenticationAsync(AuthenticatorAssertionRawResponse response, byte[] expectedChallenge, CosePublicKey storedPublicKey, uint storedSignCount, bool userVerificationRequired = false, CancellationToken cancellationToken = default)

    Validates an authenticator assertion response during authentication.

    response: AuthenticatorAssertionRawResponse
    The raw assertion response received from the browser.
    expectedChallenge: byte[]
    The expected challenge issued to the client.
    storedPublicKey: CosePublicKey
    The credential's stored COSE public key.
    storedSignCount: uint
    The last recorded signature counter for the credential.
    userVerificationRequired: bool
    A value indicating whether user verification is strictly required.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a result indicating whether authentication verification succeeded, containing the verified credential assertion model.

  • methodVerifyRegistrationAsync
    Task<Result<VerifiedCredentialRegistration>> VerifyRegistrationAsync(AuthenticatorAttestationRawResponse response, byte[] expectedChallenge, byte[] userHandle, CancellationToken cancellationToken = default)

    Validates an authenticator attestation response during registration.

    response: AuthenticatorAttestationRawResponse
    The raw attestation response received from the browser.
    expectedChallenge: byte[]
    The expected challenge issued to the client.
    userHandle: byte[]
    The expected user handle.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a result indicating whether registration verification succeeded, containing the verified credential registration model.

EricksonLopez.Security.WebAuthn.Fido2.DependencyInjection#

1
class

WebAuthnServiceCollectionExtensions

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public static class WebAuthnServiceCollectionExtensions

Provides extension methods for configuring WebAuthn / FIDO2 Relying Party services in dependency injection.

Miembros (1)

  • methodAddWebAuthnFido2
    public static IServiceCollection AddWebAuthnFido2(this IServiceCollection services, Action<WebAuthnOptions>? configureOptions = null)

    Registers WebAuthn Level 2/3 and FIDO2 Relying Party services.

    services: this IServiceCollection
    The service collection.
    configureOptions: Action<WebAuthnOptions>?
    An action to configure `WebAuthnOptions`.

    Retorna: The `IServiceCollection` instance for chaining.

    Exceptions: ArgumentNullException: `services` is `null`

EricksonLopez.Security.WebAuthn.Fido2.Enums#

9
enum

AttestationConveyancePreference

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public enum AttestationConveyancePreference

Specifies the Relying Party's preference for attestation statement conveyance during registration.

Miembros (4)

  • fieldDirect
    Direct = 3

    Specifies that the Relying Party requests direct, unaltered attestation statements from the authenticator.

  • fieldEnterprise
    Enterprise = 4

    Specifies that the Relying Party requests enterprise attestation conveying device identifiers.

  • fieldIndirect
    Indirect = 2

    Specifies that the Relying Party prefers verifiable, potentially anonymized attestation statements.

  • fieldNone
    None = 1

    Specifies that the Relying Party does not require authenticator attestation.

enum

AuthenticatorAttachment

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public enum AuthenticatorAttachment

Specifies the authenticators' acceptable attachment modalities.

Miembros (2)

  • fieldCrossPlatform
    CrossPlatform = 2

    Specifies a cross-platform roaming authenticator (e.g. USB security key, NFC, BLE).

  • fieldPlatform
    Platform = 1

    Specifies a platform authenticator attached directly to the client device (e.g. Windows Hello, Touch ID, Face ID).

enum

AuthenticatorDataFlags

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public enum AuthenticatorDataFlags : byte

Defines bit flags for the WebAuthn Authenticator Data byte.

Miembros (9)

  • fieldAttestedCredentialData
    AttestedCredentialData = 0x40

    Indicates that attested credential data is included in the authenticator data (bit 6, AT).

  • fieldBackupEligibility
    BackupEligibility = 0x08

    Indicates that the credential is eligible for backup synchronization (bit 3, BE).

  • fieldBackupState
    BackupState = 0x10

    Indicates that the credential is currently backed up (bit 4, BS).

  • fieldExtensionData
    ExtensionData = 0x80

    Indicates that extension data is included in the authenticator data (bit 7, ED).

  • fieldNone
    None = 0

    Indicates that no flags are set.

  • fieldReserved1
    Reserved1 = 0x02

    Reserved for future use (bit 1, RFU1).

  • fieldReserved2
    Reserved2 = 0x20

    Reserved for future use (bit 5, RFU2).

  • fieldUserPresent
    UserPresent = 0x01

    Indicates that user presence was verified (bit 0, UP).

  • fieldUserVerified
    UserVerified = 0x04

    Indicates that user verification succeeded via PIN or biometrics (bit 2, UV).

enum

CoseAlgorithmIdentifier

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public enum CoseAlgorithmIdentifier

Specifies cryptographic signature algorithms registered in the IANA COSE Algorithms registry.

Miembros (6)

  • fieldES256
    ES256 = -7

    Specifies ECDSA with SHA-256 over the NIST P-256 curve (COSE ID -7).

  • fieldES384
    ES384 = -35

    Specifies ECDSA with SHA-384 over the NIST P-384 curve (COSE ID -35).

  • fieldES512
    ES512 = -36

    Specifies ECDSA with SHA-512 over the NIST P-521 curve (COSE ID -36).

  • fieldEdDSA
    EdDSA = -8

    Specifies EdDSA with Ed25519 (COSE ID -8).

  • fieldPS256
    PS256 = -37

    Specifies RSASSA-PSS with SHA-256 (COSE ID -37).

  • fieldRS256
    RS256 = -257

    Specifies RSASSA-PKCS1-v1_5 with SHA-256 (COSE ID -257).

enum

CoseEllipticCurve

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public enum CoseEllipticCurve

Specifies elliptic curves registered in the IANA COSE Elliptic Curves registry (COSE parameter -1).

Miembros (4)

  • fieldEd25519
    Ed25519 = 6

    Specifies the Ed25519 curve for EdDSA.

  • fieldP256
    P256 = 1

    Specifies the NIST P-256 curve (secp256r1).

  • fieldP384
    P384 = 2

    Specifies the NIST P-384 curve (secp384r1).

  • fieldP521
    P521 = 3

    Specifies the NIST P-521 curve (secp521r1).

enum

CoseKeyType

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public enum CoseKeyType

Specifies the key type in a COSE Key structure (COSE parameter 1).

Miembros (3)

  • fieldEc2
    Ec2 = 2

    Specifies an Elliptic Curve key pair with two coordinates (x, y).

  • fieldOkp
    Okp = 1

    Specifies an Octet Key Pair (e.g. Ed25519, X25519).

  • fieldRsa
    Rsa = 3

    Specifies an RSA key pair.

enum

PublicKeyCredentialType

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public enum PublicKeyCredentialType

Specifies valid credential types for WebAuthn.

Miembros (1)

  • fieldPublicKey
    PublicKey = 1

    Specifies a public key credential type (`public-key`).

enum

ResidentKeyRequirement

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public enum ResidentKeyRequirement

Specifies the Relying Party's requirement for creating a discoverable credential (resident key / passkey).

Miembros (3)

  • fieldDiscouraged
    Discouraged = 1

    Specifies that creation of a client-side discoverable credential is discouraged.

  • fieldPreferred
    Preferred = 2

    Specifies that creation of a client-side discoverable credential is preferred if supported.

  • fieldRequired
    Required = 3

    Specifies that creation of a client-side discoverable credential is required (passkey mode).

enum

UserVerificationRequirement

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public enum UserVerificationRequirement

Specifies the Relying Party's requirements for user verification during WebAuthn ceremonies.

Miembros (3)

  • fieldDiscouraged
    Discouraged = 3

    Specifies that user verification is discouraged to minimize user friction.

  • fieldPreferred
    Preferred = 1

    Specifies that user verification is preferred but the operation will not fail if omitted.

  • fieldRequired
    Required = 2

    Specifies that user verification is strictly required (e.g. PIN or Biometrics). Ceremony fails if omitted.

EricksonLopez.Security.WebAuthn.Fido2.Mds3#

7
record

AuthenticatorMetadata

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2.Mds3
public sealed record AuthenticatorMetadata

Represents cached metadata for a single authenticator as retrieved from the FIDO Alliance MDS3.

Miembros (6)

  • constructorAuthenticatorMetadata
    public AuthenticatorMetadata(string description, IReadOnlyList<AuthenticatorStatusReport> statusReports, IReadOnlyList<byte[]> attestationRootCertificates, DateTimeOffset timeOfLastStatusChange, Guid? aaguid = null)

    Initializes a new instance of the `AuthenticatorMetadata` class with the specified metadata details.

    description: string
    The human-readable description of the authenticator model.
    statusReports: IReadOnlyList<AuthenticatorStatusReport>
    The collection of status reports associated with this authenticator.
    attestationRootCertificates: IReadOnlyList<byte[]>
    The collection of trusted root certificates for verifying attestation statements.
    timeOfLastStatusChange: DateTimeOffset
    The timestamp when this entry was last updated in MDS3.
    aaguid: Guid?
    The optional Authenticator Attestation GUID identifying this authenticator model.

    Exceptions: ArgumentNullException: `description`, `statusReports`, or `attestationRootCertificates` is `null`

  • propertyAaguid
    public Guid? Aaguid { get; init; }

    Gets the Authenticator Attestation GUID (AAGUID), uniquely identifying the authenticator model. `null` for FIDO-U2F authenticators which use KeyIdentifier instead.

  • propertyAttestationRootCertificates
    public IReadOnlyList<byte[]> AttestationRootCertificates { get; init; }

    Gets the attestation root certificates for this authenticator in DER-encoded form that validate whether the attestation certificate chain belongs to the expected manufacturer.

  • propertyDescription
    public string Description { get; init; }

    Gets the human-readable description of the authenticator (e.g. "YubiKey 5 NFC").

  • propertyStatusReports
    public IReadOnlyList<AuthenticatorStatusReport> StatusReports { get; init; }

    Gets the status reports for this authenticator from the FIDO Alliance. Consumers SHOULD reject authenticators with status NOT_FIDO_CERTIFIED, REVOKED, or USER_VERIFICATION_BYPASS.

  • propertyTimeOfLastStatusChange
    public DateTimeOffset TimeOfLastStatusChange { get; init; }

    Gets the UTC timestamp when this entry was last updated in MDS3.

enum

AuthenticatorStatus

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2.Mds3
public enum AuthenticatorStatus

Specifies FIDO Alliance authenticator status values defined by the FIDO Metadata Service.

Miembros (14)

  • fieldAttestationKeyCompromise
    AttestationKeyCompromise = 3

    Specifies that an attestation key compromise has been identified.

  • fieldFidoCertified
    FidoCertified = 1

    Specifies that the authenticator is FIDO certified at level 1.

  • fieldFidoCertifiedL1Plus
    FidoCertifiedL1Plus = 9

    Specifies that the authenticator is FIDO certified at level 1+.

  • fieldFidoCertifiedL2
    FidoCertifiedL2 = 10

    Specifies that the authenticator is FIDO certified at level 2.

  • fieldFidoCertifiedL2Plus
    FidoCertifiedL2Plus = 11

    Specifies that the authenticator is FIDO certified at level 2+.

  • fieldFidoCertifiedL3
    FidoCertifiedL3 = 12

    Specifies that the authenticator is FIDO certified at level 3.

  • fieldFidoCertifiedL3Plus
    FidoCertifiedL3Plus = 13

    Specifies that the authenticator is FIDO certified at level 3+.

  • fieldNotFidoCertified
    NotFidoCertified = 0

    Specifies that the authenticator is not yet FIDO certified.

  • fieldRevoked
    Revoked = 7

    Specifies that the device has been revoked by the vendor or FIDO Alliance.

  • fieldSelfAssertionSubmitted
    SelfAssertionSubmitted = 8

    Specifies that this authenticator self-reported using a known-invalid attestation key.

  • fieldUpdateAvailable
    UpdateAvailable = 6

    Specifies that a non-urgent software or firmware update is available.

  • fieldUserKeyPhysicalCompromise
    UserKeyPhysicalCompromise = 5

    Specifies that a physical compromise of the authenticator has been identified.

  • fieldUserKeyRemoteCompromise
    UserKeyRemoteCompromise = 4

    Specifies that a remote user key compromise has been identified.

  • fieldUserVerificationBypass
    UserVerificationBypass = 2

    Specifies that a user verification bypass vulnerability has been identified.

record

AuthenticatorStatusReport

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2.Mds3
public sealed record AuthenticatorStatusReport

Represents a status report for an authenticator from the FIDO Alliance MDS3.

Miembros (6)

  • constructorAuthenticatorStatusReport
    public AuthenticatorStatusReport(AuthenticatorStatus status, string effectiveDate, string? url = null, string? certificate = null, string? certificationLevel = null)

    Initializes a new instance of the `AuthenticatorStatusReport` class.

    status: AuthenticatorStatus
    The current certification or operational status of the authenticator.
    effectiveDate: string
    The ISO 8601 date when the status became effective.
    url: string?
    The optional URL pointing to additional information or advisory details.
    certificate: string?
    The optional base64 certificate payload for certification reports.
    certificationLevel: string?
    The optional FIDO certification level.

    Exceptions: ArgumentNullException: `effectiveDate` is `null`

  • propertyCertificate
    public string? Certificate { get; init; }

    Gets an optional certificate for FIDO_CERTIFIED reports.

  • propertyCertificationLevel
    public string? CertificationLevel { get; init; }

    Gets the FIDO certification level if applicable.

  • propertyEffectiveDate
    public string EffectiveDate { get; init; }

    Gets the date of the status report (ISO 8601 date).

  • propertyStatus
    public AuthenticatorStatus Status { get; init; }

    Gets the status of the authenticator.

  • propertyUrl
    public string? Url { get; init; }

    Gets an optional URL with more information about the status.

class

HttpMds3MetadataService

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2.Mds3
public sealed class HttpMds3MetadataService : IMds3MetadataService, IDisposable
Implementa: IDisposable, IMds3MetadataService

Provides an HTTP-backed implementation of `IMds3MetadataService` that downloads, parses, and caches FIDO Alliance MDS3 metadata.

Notas:

The FIDO MDS3 BLOB is a JWT (compact serialized) containing a JSON payload. The payload has a `entries` array where each entry has `aaguid`, `metadataStatement`, and `statusReports`. Skips full JWT signature verification by default unless `Mds3Options.ValidateJwtSignature` is `true`.

Miembros (5)

  • constructorHttpMds3MetadataService
    public HttpMds3MetadataService(HttpClient httpClient, IOptions<Mds3Options> options, ILogger<HttpMds3MetadataService> logger, TimeProvider? timeProvider = null)

    Initializes a new instance of the `HttpMds3MetadataService` class.

    httpClient: HttpClient
    The HTTP client for fetching MDS3 BLOB payloads.
    options: IOptions<Mds3Options>
    The configured MDS3 options accessor.
    logger: ILogger<HttpMds3MetadataService>
    The logger instance for diagnostic events.
    timeProvider: TimeProvider?
    The optional time provider instance.

    Exceptions: ArgumentNullException: `httpClient`, `options`, or `logger` is `null`

  • methodDispose
    public void Dispose()

    Inherits documentation from base type or interface.

  • methodGetMetadataAsync
    public async Task<Result<AuthenticatorMetadata>> GetMetadataAsync(Guid aaguid, CancellationToken cancellationToken = default)

    Retrieves the metadata for an authenticator by its AAGUID.

    aaguid: Guid
    The AAGUID of the authenticator to look up.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a `Result<T>` containing the `AuthenticatorMetadata` if found; otherwise, a failure result.

  • methodRefreshAsync
    public async Task RefreshAsync(CancellationToken cancellationToken = default)

    Forces a refresh of the MDS3 blob from the FIDO Alliance endpoint, regardless of the current cache state. Useful for background refresh jobs or testing.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodValidateAuthenticatorStatusAsync
    public async Task<Result> ValidateAuthenticatorStatusAsync(Guid aaguid, CancellationToken cancellationToken = default)

    Determines whether an authenticator with the given AAGUID is considered trustworthy based on its current status reports.

    aaguid: Guid
    The AAGUID to evaluate.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a `Result` indicating whether the authenticator is trustworthy.

interface

IMds3MetadataService

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2.Mds3
public interface IMds3MetadataService

Provides access to FIDO Alliance Metadata Service v3 (MDS3) authenticator entries.

Notas:

Implementations MUST cache the MDS3 blob and refresh it periodically (typically once per day, or whenever the `nextUpdate` field in the JWT payload has been reached).

Miembros (3)

  • methodGetMetadataAsync
    Task<Result<AuthenticatorMetadata>> GetMetadataAsync(Guid aaguid, CancellationToken cancellationToken = default)

    Retrieves the metadata for an authenticator by its AAGUID.

    aaguid: Guid
    The AAGUID of the authenticator to look up.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a `Result<T>` containing the `AuthenticatorMetadata` if found; otherwise, a failure result.

  • methodRefreshAsync
    Task RefreshAsync(CancellationToken cancellationToken = default)

    Forces a refresh of the MDS3 blob from the FIDO Alliance endpoint, regardless of the current cache state. Useful for background refresh jobs or testing.

    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation.

  • methodValidateAuthenticatorStatusAsync
    Task<Result> ValidateAuthenticatorStatusAsync(Guid aaguid, CancellationToken cancellationToken = default)

    Determines whether an authenticator with the given AAGUID is considered trustworthy based on its current status reports.

    aaguid: Guid
    The AAGUID to evaluate.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a `Result` indicating whether the authenticator is trustworthy.

class

Mds3Options

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2.Mds3
public sealed class Mds3Options

Specifies configuration options for the FIDO Alliance MDS3 metadata service.

Miembros (9)

  • propertyAllowUnknownAuthenticators
    public bool AllowUnknownAuthenticators { get; set; }

    Gets or sets a value indicating whether authenticators not found in the MDS3 metadata blob are permitted.

  • propertyCacheDuration
    public TimeSpan CacheDuration { get; set; }

    Gets or sets the duration to cache the MDS3 BLOB in memory before re-fetching. Default: 24 hours.

  • propertyDisallowedStatuses
    public AuthenticatorStatus[] DisallowedStatuses { get; set; }

    Gets or sets the set of `AuthenticatorStatus` values that cause authenticator validation to fail.

  • propertyEnforceFreshness
    public bool EnforceFreshness { get; set; }

    Gets or sets a value indicating whether to reject stale MDS3 BLOBs whose payload 'nextUpdate' has passed. Default: `true`.

  • propertyMaxClockSkew
    public TimeSpan MaxClockSkew { get; set; }

    Gets or sets the maximum clock skew tolerance for certificate validity and 'nextUpdate' checks. Default: 5 minutes.

  • propertyMetadataBlobUrl
    public string MetadataBlobUrl { get; set; }

    Gets or sets the URL of the FIDO Alliance MDS3 BLOB endpoint. Default: `https://mds3.fidoalliance.org/`.

  • propertyRevocationMode
    public System.Security.Cryptography.X509Certificates.X509RevocationMode RevocationMode { get; set; }

    Gets or sets the certificate revocation mode for MDS3 certificate chain verification. Default: `X509RevocationMode.Online`.

  • propertyTrustedRootCertificates
    public IList<System.Security.Cryptography.X509Certificates.X509Certificate2> TrustedRootCertificates { get; set; }

    Gets the list of trusted root certificates used to anchor MDS3 JWT certificate chain validation. If empty, the default official FIDO Alliance root certificates (GlobalSign Root R3 and R46) are used.

  • propertyValidateJwtSignature
    public bool ValidateJwtSignature { get; set; }

    Gets or sets a value indicating whether to validate the MDS3 BLOB JWT signature against the FIDO Alliance root certificate.

class

Mds3ServiceCollectionExtensions

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2.Mds3
public static class Mds3ServiceCollectionExtensions

Provides extension methods to register FIDO Alliance MDS3 metadata services into the DI container.

Miembros (1)

  • methodAddFidoMds3
    public static IServiceCollection AddFidoMds3(this IServiceCollection services, Action<Mds3Options>? configureOptions = null)

    Adds the FIDO Alliance MDS3 metadata service to the dependency injection container.

    services: this IServiceCollection
    The service collection.
    configureOptions: Action<Mds3Options>?
    The optional configuration delegate for `Mds3Options`.

    Retorna: The same service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null` Example:

    builder.Services
        .AddWebAuthnFido2(opts => opts.RelyingPartyId = "example.com")
        .AddFidoMds3(opts =>
        {
            opts.AllowUnknownAuthenticators = false;  // strict: only MDS3-listed authenticators
            opts.CacheDuration = TimeSpan.FromHours(12);
        });

EricksonLopez.Security.WebAuthn.Fido2.Mds3.Services#

1
class

Mds3AttestationTrustStore

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2.Mds3
public sealed class Mds3AttestationTrustStore : IAttestationTrustStore
Implementa: IAttestationTrustStore

Implements `IAttestationTrustStore` by retrieving trusted root certificates from FIDO MDS3 metadata.

Miembros (2)

  • constructorMds3AttestationTrustStore
    public Mds3AttestationTrustStore(IMds3MetadataService mds3Service, IOptions<WebAuthnOptions> options)

    Initializes a new instance of the `Mds3AttestationTrustStore` class.

    mds3Service: IMds3MetadataService
    The MDS3 metadata service.
    options: IOptions<WebAuthnOptions>
    The WebAuthn configuration options.
  • methodGetTrustAnchors
    public IReadOnlyList<X509Certificate2> GetTrustAnchors(string format, Guid? aaguid)

    Gets the trusted root certificates for the specified attestation format and optional AAGUID.

    format: string
    The attestation statement format (e.g. "packed", "fido-u2f", "android-safetynet", "tpm").
    aaguid: Guid?
    The optional Authenticator Attestation GUID (AAGUID).

    Retorna: A collection of trusted root certificates, or empty if none are known.

EricksonLopez.Security.WebAuthn.Fido2.Models#

17
record

AttestationObject

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed record AttestationObject

Represents the parsed WebAuthn attestation object (CBOR map containing fmt, attStmt, and authData).

Miembros (5)

  • constructorAttestationObject
    public AttestationObject(AuthenticatorData authenticatorData, AttestationStatement statement, byte[] rawBytes)

    Initializes a new instance of the `AttestationObject` record with the specified authenticator data, statement, and raw bytes.

    authenticatorData: AuthenticatorData
    The parsed authenticator data.
    statement: AttestationStatement
    The parsed attestation statement.
    rawBytes: byte[]
    The raw CBOR-encoded attestation object bytes.

    Exceptions: ArgumentNullException: `authenticatorData`, `statement`, or `rawBytes` is `null`

  • propertyAuthenticatorData
    public AuthenticatorData AuthenticatorData { get; init; }

    Gets the parsed authenticator data.

  • propertyFormat
    public string Format { get; }

    Gets the attestation format identifier.

  • propertyRawBytes
    public byte[] RawBytes { get; init; }

    Gets the raw CBOR-encoded attestation object bytes.

  • propertyStatement
    public AttestationStatement Statement { get; init; }

    Gets the parsed attestation statement.

record

AttestationStatement

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed record AttestationStatement

Represents the parsed attestation statement from an attestation object.

Miembros (6)

  • constructorAttestationStatement
    public AttestationStatement(string format, byte[] rawBytes, byte[]? signature = null, long? algorithm = null, IReadOnlyList<byte[]>? x5c = null)

    Initializes a new instance of the `AttestationStatement` record with the specified format and statement data.

    format: string
    The attestation format identifier (e.g., "none", "packed", "tpm").
    rawBytes: byte[]
    The raw CBOR bytes of the attestation statement.
    signature: byte[]?
    The optional signature bytes if present in the statement.
    algorithm: long?
    The optional COSE algorithm identifier.
    x5c: IReadOnlyList<byte[]>?
    The optional X.509 certificate chain encoded as raw DER bytes.

    Exceptions: ArgumentNullException: `rawBytes` is `null`; ArgumentException: `format` is `null`, empty, or whitespace

  • propertyAlgorithm
    public long? Algorithm { get; init; }

    Gets the algorithm identifier if present in the attestation statement.

  • propertyFormat
    public string Format { get; init; }

    Gets the attestation format identifier (e.g. "none", "packed", "fido-u2f", "android-key", "tpm", "apple").

  • propertyRawBytes
    public byte[] RawBytes { get; init; }

    Gets the raw CBOR map representing the attestation statement.

  • propertySignature
    public byte[]? Signature { get; init; }

    Gets the signature bytes if present in the attestation statement.

  • propertyX5c
    public IReadOnlyList<byte[]>? X5c { get; init; }

    Gets the X.509 certificate chain (x5c) encoded as raw DER bytes if present.

record

AttestedCredentialData

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed record AttestedCredentialData

Represents the Attested Credential Data structure parsed from an authenticator registration response.

Miembros (5)

  • constructorAttestedCredentialData
    public AttestedCredentialData(Guid aaguid, byte[] credentialId, CosePublicKey publicKey, byte[] rawBytes)

    Initializes a new instance of the `AttestedCredentialData` record with the specified AAGUID, credential ID, public key, and raw bytes.

    aaguid: Guid
    The Authenticator Attestation GUID (AAGUID).
    credentialId: byte[]
    The unique Credential ID generated by the authenticator.
    publicKey: CosePublicKey
    The parsed COSE public key.
    rawBytes: byte[]
    The raw bytes of the attested credential data.

    Exceptions: ArgumentNullException: `credentialId`, `publicKey`, or `rawBytes` is `null`

  • propertyAaguid
    public Guid Aaguid { get; init; }

    Gets the Authenticator Attestation GUID (AAGUID, 16 bytes).

  • propertyCredentialId
    public byte[] CredentialId { get; init; }

    Gets the unique Credential ID generated by the authenticator.

  • propertyPublicKey
    public CosePublicKey PublicKey { get; init; }

    Gets the parsed COSE public key.

  • propertyRawBytes
    public byte[] RawBytes { get; init; }

    Gets the raw bytes of the attested credential data.

record

AuthenticatorAssertionRawResponse

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed record AuthenticatorAssertionRawResponse

Represents the raw response payload returned from the client browser after `navigator.credentials.get()`.

Miembros (7)

  • constructorAuthenticatorAssertionRawResponse
    public AuthenticatorAssertionRawResponse(string id, byte[] rawId, byte[] clientDataJson, byte[] authenticatorData, byte[] signature, byte[]? userHandle = null)

    Initializes a new instance of the `AuthenticatorAssertionRawResponse` record with the specified response components.

    id: string
    The base64url-encoded credential identifier.
    rawId: byte[]
    The raw binary credential ID.
    clientDataJson: byte[]
    The UTF-8 JSON bytes of clientDataJSON.
    authenticatorData: byte[]
    The raw binary authenticatorData bytes.
    signature: byte[]
    The raw binary signature produced by the authenticator.
    userHandle: byte[]?
    The optional user handle.

    Exceptions: ArgumentNullException: `rawId`, `clientDataJson`, `authenticatorData`, or `signature` is `null`; ArgumentException: `id` is `null`, empty, or whitespace

  • propertyAuthenticatorData
    public byte[] AuthenticatorData { get; init; }

    Gets the raw binary authenticatorData bytes.

  • propertyClientDataJson
    public byte[] ClientDataJson { get; init; }

    Gets the UTF-8 JSON bytes of clientDataJSON.

  • propertyId
    public string Id { get; init; }

    Gets the base64url-encoded credential identifier.

  • propertyRawId
    public byte[] RawId { get; init; }

    Gets the raw binary credential ID.

  • propertySignature
    public byte[] Signature { get; init; }

    Gets the raw binary signature produced by the authenticator over `authData || SHA256(clientDataJSON)`.

  • propertyUserHandle
    public byte[]? UserHandle { get; init; }

    Gets the optional user handle (opaque user identifier returned in discoverable / passkey flows).

record

AuthenticatorAttestationRawResponse

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed record AuthenticatorAttestationRawResponse

Represents the raw response payload returned from the client browser after `navigator.credentials.create()`.

Miembros (5)

  • constructorAuthenticatorAttestationRawResponse
    public AuthenticatorAttestationRawResponse(string id, byte[] rawId, byte[] clientDataJson, byte[] attestationObject)

    Initializes a new instance of the `AuthenticatorAttestationRawResponse` record with the specified response components.

    id: string
    The base64url-encoded credential identifier.
    rawId: byte[]
    The raw binary credential ID.
    clientDataJson: byte[]
    The UTF-8 JSON bytes of clientDataJSON.
    attestationObject: byte[]
    The raw CBOR-encoded bytes of attestationObject.

    Exceptions: ArgumentNullException: `rawId`, `clientDataJson`, or `attestationObject` is `null`; ArgumentException: `id` is `null`, empty, or whitespace

  • propertyAttestationObject
    public byte[] AttestationObject { get; init; }

    Gets the raw CBOR-encoded bytes of attestationObject.

  • propertyClientDataJson
    public byte[] ClientDataJson { get; init; }

    Gets the UTF-8 JSON bytes of clientDataJSON.

  • propertyId
    public string Id { get; init; }

    Gets the base64url-encoded credential identifier.

  • propertyRawId
    public byte[] RawId { get; init; }

    Gets the raw binary credential ID.

record

AuthenticatorData

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed record AuthenticatorData

Represents the parsed WebAuthn Authenticator Data structure.

Miembros (11)

  • constructorAuthenticatorData
    public AuthenticatorData(byte[] rpIdHash, AuthenticatorDataFlags flags, uint signCount, byte[] rawBytes, AttestedCredentialData? attestedCredentialData = null, byte[]? extensionData = null)

    Initializes a new instance of the `AuthenticatorData` record with parsed flags, counter, and optional payload data.

    rpIdHash: byte[]
    The SHA-256 hash of the Relying Party ID.
    flags: AuthenticatorDataFlags
    The authenticator data bit flags.
    signCount: uint
    The signature counter value.
    rawBytes: byte[]
    The raw binary bytes of the authenticator data.
    attestedCredentialData: AttestedCredentialData?
    The optional attested credential data.
    extensionData: byte[]?
    The optional raw extension data bytes.

    Exceptions: ArgumentNullException: `rpIdHash` or `rawBytes` is `null`

  • propertyAttestedCredentialData
    public AttestedCredentialData? AttestedCredentialData { get; init; }

    Gets the attested credential data, present if `AuthenticatorDataFlags.AttestedCredentialData` flag is set.

  • propertyBackupEligibility
    public bool BackupEligibility { get; }

    Gets a value indicating whether the Backup Eligibility (BE) bit was set (passkey capability).

  • propertyBackupState
    public bool BackupState { get; }

    Gets a value indicating whether the Backup State (BS) bit was set (synced passkey).

  • propertyExtensionData
    public byte[]? ExtensionData { get; init; }

    Gets the raw extension data bytes, present if `AuthenticatorDataFlags.ExtensionData` flag is set.

  • propertyFlags
    public AuthenticatorDataFlags Flags { get; init; }

    Gets the bit flags (UserPresent, UserVerified, AttestedCredentialData, etc.).

  • propertyRawBytes
    public byte[] RawBytes { get; init; }

    Gets the raw binary representation of the Authenticator Data.

  • propertyRpIdHash
    public byte[] RpIdHash { get; init; }

    Gets the SHA-256 hash of the Relying Party ID (32 bytes).

  • propertySignCount
    public uint SignCount { get; init; }

    Gets the signature counter (32-bit big-endian integer, detecting cloned authenticators).

  • propertyUserPresent
    public bool UserPresent { get; }

    Gets a value indicating whether the User Present (UP) bit was set.

  • propertyUserVerified
    public bool UserVerified { get; }

    Gets a value indicating whether the User Verified (UV) bit was set.

record

CollectedClientData

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed record CollectedClientData

Represents the parsed JSON data sent by the browser client in `clientDataJSON`.

Miembros (6)

  • constructorCollectedClientData
    public CollectedClientData(string type, string challenge, string origin, byte[] rawClientDataJson, bool? crossOrigin = null)

    Initializes a new instance of the `CollectedClientData` record with the specified client data parameters.

    type: string
    The operation type (`webauthn.create` or `webauthn.get`).
    challenge: string
    The base64url-encoded challenge sent by the server.
    origin: string
    The fully-qualified origin of the caller.
    rawClientDataJson: byte[]
    The raw UTF-8 bytes of the client data JSON.
    crossOrigin: bool?
    The optional value indicating whether the request was executed in a cross-origin iframe context.

    Exceptions: ArgumentNullException: `rawClientDataJson` is `null`; ArgumentException: `type`, `challenge`, or `origin` is `null`, empty, or whitespace

  • propertyChallenge
    public string Challenge { get; init; }

    Gets the base64url-encoded challenge sent by the server.

  • propertyCrossOrigin
    public bool? CrossOrigin { get; init; }

    Gets a value indicating whether the request was executed in a cross-origin iframe context.

  • propertyOrigin
    public string Origin { get; init; }

    Gets the fully-qualified origin of the caller (e.g. `https://example.com:443`).

  • propertyRawClientDataJson
    public byte[] RawClientDataJson { get; init; }

    Gets the raw UTF-8 bytes of the client data JSON.

  • propertyType
    public string Type { get; init; }

    Gets the operation type (`webauthn.create` for registration, `webauthn.get` for authentication).

record

CosePublicKey

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed record CosePublicKey

Represents a parsed COSE public key extracted from an authenticator's attested credential data.

Miembros (9)

  • constructorCosePublicKey
    public CosePublicKey(CoseKeyType keyType, CoseAlgorithmIdentifier algorithm, byte[] rawBytes, CoseEllipticCurve? curve = null, byte[]? x = null, byte[]? y = null, byte[]? modulus = null, byte[]? exponent = null)

    Initializes a new instance of the `CosePublicKey` record with the specified key parameters.

    keyType: CoseKeyType
    The COSE Key Type (e.g., EC2, RSA, OKP).
    algorithm: CoseAlgorithmIdentifier
    The cryptographic algorithm identifier.
    rawBytes: byte[]
    The raw CBOR-encoded bytes of the COSE Key.
    curve: CoseEllipticCurve?
    The optional curve identifier for EC2 or OKP keys.
    x: byte[]?
    The optional X coordinate or public key bytes.
    y: byte[]?
    The optional Y coordinate bytes for EC2 keys.
    modulus: byte[]?
    The optional RSA modulus (N) bytes.
    exponent: byte[]?
    The optional RSA public exponent (E) bytes.

    Exceptions: ArgumentNullException: `rawBytes` is `null`

  • propertyAlgorithm
    public CoseAlgorithmIdentifier Algorithm { get; init; }

    Gets the cryptographic algorithm identifier (e.g. ES256 = -7, RS256 = -257, EdDSA = -8).

  • propertyCurve
    public CoseEllipticCurve? Curve { get; init; }

    Gets the curve identifier for EC2 or OKP keys (e.g. P-256 = 1, Ed25519 = 6).

  • propertyExponent
    public byte[]? Exponent { get; init; }

    Gets the RSA Public Exponent (E) bytes for RSA keys.

  • propertyKeyType
    public CoseKeyType KeyType { get; init; }

    Gets the COSE Key Type (e.g. EC2 = 2, RSA = 3, OKP = 1).

  • propertyModulus
    public byte[]? Modulus { get; init; }

    Gets the RSA Modulus (N) bytes for RSA keys.

  • propertyRawBytes
    public byte[] RawBytes { get; init; }

    Gets the raw CBOR-encoded bytes of the COSE Key.

  • propertyX
    public byte[]? X { get; init; }

    Gets the X coordinate bytes for EC2 keys, or public key bytes for OKP (Ed25519) keys.

  • propertyY
    public byte[]? Y { get; init; }

    Gets the Y coordinate bytes for EC2 keys.

record

CredentialCreateOptions

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed record CredentialCreateOptions

Represents all configuration parameters required by `navigator.credentials.create()` to generate a new WebAuthn credential.

Miembros (11)

  • constructorCredentialCreateOptions
    public CredentialCreateOptions(RelyingPartyIdentity rp, PublicKeyCredentialUserEntity user, byte[] challenge, IReadOnlyList<PublicKeyCredentialParameters> pubKeyCredParams)

    Initializes a new instance of the `CredentialCreateOptions` record with the required Relying Party, user, challenge, and cryptographic parameters.

    rp: RelyingPartyIdentity
    The Relying Party identity information.
    user: PublicKeyCredentialUserEntity
    The user entity account information.
    challenge: byte[]
    The cryptographically random challenge byte array generated by the server.
    pubKeyCredParams: IReadOnlyList<PublicKeyCredentialParameters>
    The list of supported cryptographic parameters.

    Exceptions: ArgumentNullException: `rp`, `user`, `challenge`, or `pubKeyCredParams` is `null`

  • propertyAttestation
    public AttestationConveyancePreference Attestation { get; init; }

    Gets the attestation conveyance preference (default is None for privacy).

  • propertyAuthenticatorAttachment
    public AuthenticatorAttachment? AuthenticatorAttachment { get; init; }

    Gets the authenticator attachment modality preference (e.g. Platform vs CrossPlatform).

  • propertyChallenge
    public byte[] Challenge { get; init; }

    Gets the cryptographically random challenge byte array generated by the server.

  • propertyExcludeCredentials
    public IReadOnlyList<PublicKeyCredentialDescriptor>? ExcludeCredentials { get; init; }

    Gets the optional list of credentials already registered for this user (to prevent re-registering the same authenticator).

  • propertyPubKeyCredParams
    public IReadOnlyList<PublicKeyCredentialParameters> PubKeyCredParams { get; init; }

    Gets the list of supported cryptographic parameters.

  • propertyResidentKey
    public ResidentKeyRequirement ResidentKey { get; init; }

    Gets the resident key / discoverable credential requirement (Passkey mode).

  • propertyRp
    public RelyingPartyIdentity Rp { get; init; }

    Gets the Relying Party information.

  • propertyTimeoutMilliseconds
    public ulong TimeoutMilliseconds { get; init; }

    Gets the timeout in milliseconds for the ceremony.

  • propertyUser
    public PublicKeyCredentialUserEntity User { get; init; }

    Gets the user entity information.

  • propertyUserVerification
    public UserVerificationRequirement UserVerification { get; init; }

    Gets the user verification requirement (e.g. Preferred or Required).

record

CredentialRequestOptions

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed record CredentialRequestOptions

Represents all configuration parameters required by `navigator.credentials.get()` to authenticate with an existing WebAuthn credential.

Miembros (6)

  • constructorCredentialRequestOptions
    public CredentialRequestOptions(byte[] challenge, string rpId)

    Initializes a new instance of the `CredentialRequestOptions` record with the specified challenge and Relying Party identifier.

    challenge: byte[]
    The cryptographically random challenge byte array generated by the server.
    rpId: string
    The Relying Party identifier (domain name).

    Exceptions: ArgumentNullException: `challenge` is `null`; ArgumentException: `rpId` is `null`, empty, or whitespace

  • propertyAllowCredentials
    public IReadOnlyList<PublicKeyCredentialDescriptor>? AllowCredentials { get; init; }

    Gets the optional list of allowed credentials (omitted in discoverable credential / passkey autofill ceremonies).

  • propertyChallenge
    public byte[] Challenge { get; init; }

    Gets the cryptographically random challenge byte array generated by the server.

  • propertyRpId
    public string RpId { get; init; }

    Gets the Relying Party identifier (domain name, e.g. "example.com").

  • propertyTimeoutMilliseconds
    public ulong TimeoutMilliseconds { get; init; }

    Gets the timeout in milliseconds for the ceremony.

  • propertyUserVerification
    public UserVerificationRequirement UserVerification { get; init; }

    Gets the user verification requirement (e.g. Preferred or Required).

record

PublicKeyCredentialDescriptor

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed record PublicKeyCredentialDescriptor

Represents the attributes necessary to identify a public key credential.

Miembros (4)

  • constructorPublicKeyCredentialDescriptor
    public PublicKeyCredentialDescriptor(byte[] id, IReadOnlyList<string>? transports = null)

    Initializes a new instance of the `PublicKeyCredentialDescriptor` record.

    id: byte[]
    The credential ID byte array.
    transports: IReadOnlyList<string>?
    Optional transport hints (e.g. "usb", "nfc", "ble", "internal").

    Exceptions: ArgumentNullException: `id` is `null`

  • propertyId
    public byte[] Id { get; init; }

    Gets the credential ID (binary identifier generated by the authenticator).

  • propertyTransports
    public IReadOnlyList<string>? Transports { get; init; }

    Gets the optional list of transport hints for reaching the authenticator.

  • propertyType
    public PublicKeyCredentialType Type { get; init; }

    Gets the credential type.

record

PublicKeyCredentialParameters

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed record PublicKeyCredentialParameters

Specifies the desired credential properties (type and cryptographic algorithm).

Miembros (3)

  • constructorPublicKeyCredentialParameters
    public PublicKeyCredentialParameters(CoseAlgorithmIdentifier alg)

    Initializes a new instance of the `PublicKeyCredentialParameters` record.

    alg: CoseAlgorithmIdentifier
    The COSE algorithm identifier.
  • propertyAlg
    public CoseAlgorithmIdentifier Alg { get; init; }

    Gets the cryptographic algorithm identifier (e.g. ES256 = -7, RS256 = -257).

  • propertyType
    public PublicKeyCredentialType Type { get; init; }

    Gets the credential type (always `PublicKeyCredentialType.PublicKey`).

record

PublicKeyCredentialUserEntity

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed record PublicKeyCredentialUserEntity

Represents a user account entity for which a public key credential is created.

Miembros (5)

  • constructorPublicKeyCredentialUserEntity
    public PublicKeyCredentialUserEntity(byte[] id, string name, string displayName, string? icon = null)

    Initializes a new instance of the `PublicKeyCredentialUserEntity` record with the specified user account details.

    id: byte[]
    The user handle opaque byte sequence identifying the user account (between 1 and 64 bytes).
    name: string
    The user's account identifier (e.g., username or email address).
    displayName: string
    The user's friendly display name.
    icon: string?
    The optional icon URL for the user entity.

    Exceptions: ArgumentNullException: `id` is `null`; ArgumentOutOfRangeException: `id` length is 0 or greater than 64 bytes; ArgumentException: `name` or `displayName` is `null`, empty, or whitespace

  • propertyDisplayName
    public string DisplayName { get; init; }

    Gets the user's friendly display name (e.g. "Erickson Lopez").

  • propertyIcon
    public string? Icon { get; init; }

    Gets an optional icon URL for the user entity.

  • propertyId
    public byte[] Id { get; init; }

    Gets the user handle (an opaque byte sequence identifying the user account, max 64 bytes).

  • propertyName
    public string Name { get; init; }

    Gets the user's account identifier (e.g. username or email address).

record

RelyingPartyIdentity

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed record RelyingPartyIdentity

Represents the Relying Party (RP) identity in WebAuthn ceremonies.

Miembros (4)

  • constructorRelyingPartyIdentity
    public RelyingPartyIdentity(string id, string name, string? icon = null)

    Initializes a new instance of the `RelyingPartyIdentity` record.

    id: string
    The RP identifier domain name.
    name: string
    The RP display name.
    icon: string?
    The optional icon URL.

    Exceptions: ArgumentException: `id` or `name` is `null`, empty, or whitespace

  • propertyIcon
    public string? Icon { get; init; }

    Gets an optional icon URL for the Relying Party.

  • propertyId
    public string Id { get; init; }

    Gets the unique Relying Party identifier (domain name, e.g. "example.com" or "localhost").

  • propertyName
    public string Name { get; init; }

    Gets the human-palatable name of the Relying Party (e.g. "EricksonLopez Corporation").

record

VerifiedCredentialAssertion

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed record VerifiedCredentialAssertion

Represents the validated output of a WebAuthn credential assertion (authentication) ceremony.

Miembros (7)

  • constructorVerifiedCredentialAssertion
    public VerifiedCredentialAssertion(byte[] credentialId, uint updatedSignCount, bool userVerified, bool userPresent, bool isBackedUp, byte[]? userHandle = null)

    Initializes a new instance of the `VerifiedCredentialAssertion` record with the ceremony verification results.

    credentialId: byte[]
    The binary credential identifier that authenticated.
    updatedSignCount: uint
    The updated signature counter to be persisted in storage.
    userVerified: bool
    A value indicating whether user verification was successfully performed.
    userPresent: bool
    A value indicating whether the user was confirmed present.
    isBackedUp: bool
    A value indicating whether the credential is confirmed backed up.
    userHandle: byte[]?
    The optional user handle returned by the authenticator.

    Exceptions: ArgumentNullException: `credentialId` is `null`

  • propertyCredentialId
    public byte[] CredentialId { get; init; }

    Gets the credential identifier that authenticated.

  • propertyIsBackedUp
    public bool IsBackedUp { get; init; }

    Gets a value indicating whether the credential is confirmed backed up / passkey synced.

  • propertyUpdatedSignCount
    public uint UpdatedSignCount { get; init; }

    Gets the updated signature counter to be persisted in storage.

  • propertyUserHandle
    public byte[]? UserHandle { get; init; }

    Gets the optional user handle returned by the authenticator.

  • propertyUserPresent
    public bool UserPresent { get; init; }

    Gets a value indicating whether the credential was confirmed present via user interaction.

  • propertyUserVerified
    public bool UserVerified { get; init; }

    Gets a value indicating whether user verification (biometrics or PIN) was successfully performed.

record

VerifiedCredentialRegistration

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed record VerifiedCredentialRegistration

Represents the validated output of a WebAuthn credential registration ceremony, ready for persistence in storage.

Miembros (9)

  • constructorVerifiedCredentialRegistration
    public VerifiedCredentialRegistration(byte[] credentialId, byte[] userHandle, CosePublicKey publicKey, uint signCount, Guid aaguid, bool isBackupEligible, bool isBackedUp, string attestationFormat)

    Initializes a new instance of the `VerifiedCredentialRegistration` record with ceremony verification results.

    credentialId: byte[]
    The unique binary credential identifier.
    userHandle: byte[]
    The user handle associated with the credential.
    publicKey: CosePublicKey
    The validated COSE public key.
    signCount: uint
    The initial signature counter.
    aaguid: Guid
    The Authenticator Attestation GUID (AAGUID).
    isBackupEligible: bool
    A value indicating whether the credential is a discoverable passkey capable of multi-device synchronization.
    isBackedUp: bool
    A value indicating whether the credential is currently synced/backed up.
    attestationFormat: string
    The verified attestation format identifier.

    Exceptions: ArgumentNullException: `credentialId`, `userHandle`, `publicKey`, or `attestationFormat` is `null`

  • propertyAaguid
    public Guid Aaguid { get; init; }

    Gets the Authenticator Attestation GUID (AAGUID).

  • propertyAttestationFormat
    public string AttestationFormat { get; init; }

    Gets the attestation format verified (e.g. "none" or "packed").

  • propertyCredentialId
    public byte[] CredentialId { get; init; }

    Gets the unique credential identifier.

  • propertyIsBackedUp
    public bool IsBackedUp { get; init; }

    Gets a value indicating whether the credential is currently synced/backed up.

  • propertyIsBackupEligible
    public bool IsBackupEligible { get; init; }

    Gets a value indicating whether the credential is a discoverable passkey capable of multi-device synchronization.

  • propertyPublicKey
    public CosePublicKey PublicKey { get; init; }

    Gets the validated COSE public key.

  • propertySignCount
    public uint SignCount { get; init; }

    Gets the initial signature counter (typically 0).

  • propertyUserHandle
    public byte[] UserHandle { get; init; }

    Gets the user handle associated with the credential.

class

WebAuthnOptions

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed class WebAuthnOptions

Specifies global configuration options for the WebAuthn / FIDO2 Relying Party engine.

Miembros (12)

  • propertyAllowCrossOrigin
    public bool AllowCrossOrigin { get; set; }

    Gets or sets whether cross-origin requests in clientDataJSON are permitted. Default is false per W3C WebAuthn Level 3 §7.1 / §7.2.

  • propertyAllowNoneAttestation
    public bool AllowNoneAttestation { get; set; }

    Gets or sets whether "none" attestation is permitted. Default is true (standard passkey support).

  • propertyAllowUntrustedAttestation
    public bool AllowUntrustedAttestation { get; set; }

    Gets or sets whether untrusted self-signed attestation certificates are accepted. Default is false (strict Zero-Trust).

  • propertyAllowedOrigins
    public ISet<string> AllowedOrigins { get; set; }

    Gets or sets the expected application origins (e.g. "https://example.com", "http://localhost:5000").

  • propertyAttestationRootCertificates
    public ICollection<System.Security.Cryptography.X509Certificates.X509Certificate2> AttestationRootCertificates { get; set; }

    Gets or sets trusted root certificates for validating attestation statement x5c chains.

  • propertyCeremonyTimeoutMilliseconds
    public ulong CeremonyTimeoutMilliseconds { get; set; }

    Gets or sets the ceremony timeout in milliseconds.

  • propertyChallengeLengthBytes
    public int ChallengeLengthBytes { get; set; }

    Gets or sets the challenge length in bytes (minimum 32 bytes).

  • propertyDefaultResidentKey
    public ResidentKeyRequirement DefaultResidentKey { get; set; }

    Gets or sets the default resident key requirement.

  • propertyDefaultUserVerification
    public UserVerificationRequirement DefaultUserVerification { get; set; }

    Gets or sets the default user verification requirement.

  • propertyRpId
    public string RpId { get; set; }

    Gets or sets the Relying Party identifier (domain name, e.g. "example.com" or "localhost").

  • propertyRpName
    public string RpName { get; set; }

    Gets or sets the Relying Party display name.

  • propertySupportedAlgorithms
    public IList<CoseAlgorithmIdentifier> SupportedAlgorithms { get; set; }

    Gets or sets the supported cryptographic algorithms in order of preference.

EricksonLopez.Security.WebAuthn.Fido2.Parsers#

2
class

AuthenticatorDataParser

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed class AuthenticatorDataParser : IAuthenticatorDataParser
Implementa: IAuthenticatorDataParser

Parses binary WebAuthn Authenticator Data byte sequences.

Miembros (2)

  • constructorAuthenticatorDataParser
    public AuthenticatorDataParser(ICoseKeyParser coseKeyParser)

    Initializes a new instance of the `AuthenticatorDataParser` class.

    coseKeyParser: ICoseKeyParser
    The COSE key parser implementation.

    Exceptions: ArgumentNullException: `coseKeyParser` is `null`

  • methodParse
    public Result<AuthenticatorData> Parse(ReadOnlySpan<byte> authDataBytes)

    Parses an Authenticator Data structure from a byte span.

    authDataBytes: ReadOnlySpan<byte>
    The binary authenticatorData span.

    Retorna: A result containing the parsed `AuthenticatorData` or an error.

class

CoseKeyParser

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed class CoseKeyParser : ICoseKeyParser
Implementa: ICoseKeyParser

Decodes CBOR-encoded COSE Key structures into `CosePublicKey` models.

Miembros (1)

  • methodParse
    public Result<CosePublicKey> Parse(ReadOnlySpan<byte> cborBytes)

    Parses a CBOR-encoded COSE Key map from a byte span.

    cborBytes: ReadOnlySpan<byte>
    The raw CBOR byte span.

    Retorna: A result containing the parsed `CosePublicKey` or an error.

EricksonLopez.Security.WebAuthn.Fido2.Services#

2
class

DefaultAttestationTrustStore

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed class DefaultAttestationTrustStore : IAttestationTrustStore
Implementa: IAttestationTrustStore

Default implementation of `IAttestationTrustStore` using roots configured in `WebAuthnOptions`.

Miembros (2)

  • constructorDefaultAttestationTrustStore
    public DefaultAttestationTrustStore(IOptions<WebAuthnOptions> options)

    Initializes a new instance of the `DefaultAttestationTrustStore` class.

    options: IOptions<WebAuthnOptions>
    The WebAuthn options.
  • methodGetTrustAnchors
    public IReadOnlyList<X509Certificate2> GetTrustAnchors(string format, Guid? aaguid)

    Gets the trusted root certificates for the specified attestation format and optional AAGUID.

    format: string
    The attestation statement format (e.g. "packed", "fido-u2f", "android-safetynet", "tpm").
    aaguid: Guid?
    The optional Authenticator Attestation GUID (AAGUID).

    Retorna: A collection of trusted root certificates, or empty if none are known.

class

WebAuthnCeremonyService

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed class WebAuthnCeremonyService : IWebAuthnCeremonyService
Implementa: IWebAuthnCeremonyService

Coordinates WebAuthn Level 2/3 and FIDO2 Relying Party registration and authentication ceremonies.

Miembros (5)

  • constructorWebAuthnCeremonyService
    public WebAuthnCeremonyService(IOptions<WebAuthnOptions> options, IAuthenticatorDataParser authDataParser, IEnumerable<IAttestationVerifier> attestationVerifiers, ILogger<WebAuthnCeremonyService>? logger = null)

    Initializes a new instance of the `WebAuthnCeremonyService` class with required parsers and verifiers.

    options: IOptions<WebAuthnOptions>
    The configured WebAuthn options.
    authDataParser: IAuthenticatorDataParser
    The authenticator data parser.
    attestationVerifiers: IEnumerable<IAttestationVerifier>
    The collection of registered attestation statement verifiers.
    logger: ILogger<WebAuthnCeremonyService>?
    The optional logger instance.

    Exceptions: ArgumentNullException: `options`, `authDataParser`, or `attestationVerifiers` is `null`

  • methodCreateAuthenticationOptions
    public CredentialRequestOptions CreateAuthenticationOptions(CredentialRequestOptions? customOptions = null)

    Generates the options payload required to initiate a credential assertion (authentication) ceremony.

    customOptions: CredentialRequestOptions?
    Optional overrides for default options.

    Retorna: A new `CredentialRequestOptions` instance containing a fresh cryptographic challenge.

  • methodCreateRegistrationOptions
    public CredentialCreateOptions CreateRegistrationOptions(PublicKeyCredentialUserEntity user, CredentialCreateOptions? customOptions = null)

    Generates the options payload required to initiate a credential creation ceremony.

    user: PublicKeyCredentialUserEntity
    The user entity creating the credential.
    customOptions: CredentialCreateOptions?
    Optional overrides for default options.

    Retorna: A new `CredentialCreateOptions` instance containing a fresh cryptographic challenge.

  • methodVerifyAuthenticationAsync
    public Task<Result<VerifiedCredentialAssertion>> VerifyAuthenticationAsync(AuthenticatorAssertionRawResponse response, byte[] expectedChallenge, CosePublicKey storedPublicKey, uint storedSignCount, bool userVerificationRequired = false, CancellationToken cancellationToken = default)

    Validates an authenticator assertion response during authentication.

    response: AuthenticatorAssertionRawResponse
    The raw assertion response received from the browser.
    expectedChallenge: byte[]
    The expected challenge issued to the client.
    storedPublicKey: CosePublicKey
    The credential's stored COSE public key.
    storedSignCount: uint
    The last recorded signature counter for the credential.
    userVerificationRequired: bool
    A value indicating whether user verification is strictly required.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a result indicating whether authentication verification succeeded, containing the verified credential assertion model.

  • methodVerifyRegistrationAsync
    public Task<Result<VerifiedCredentialRegistration>> VerifyRegistrationAsync(AuthenticatorAttestationRawResponse response, byte[] expectedChallenge, byte[] userHandle, CancellationToken cancellationToken = default)

    Validates an authenticator attestation response during registration.

    response: AuthenticatorAttestationRawResponse
    The raw attestation response received from the browser.
    expectedChallenge: byte[]
    The expected challenge issued to the client.
    userHandle: byte[]
    The expected user handle.
    cancellationToken: CancellationToken
    A token that can be used to cancel the asynchronous operation.

    Retorna: A task representing the asynchronous operation. The task result contains a result indicating whether registration verification succeeded, containing the verified credential registration model.

EricksonLopez.Security.WebAuthn.Fido2.Verifiers#

5
class

AndroidSafetyNetAttestationVerifier

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed class AndroidSafetyNetAttestationVerifier : IAttestationVerifier
Implementa: IAttestationVerifier

Verifies the "android-safetynet" WebAuthn attestation statement format.

Notas:

Android SafetyNet attestation uses a signed JWT (JSON Web Token) issued by Google's SafetyNet API. The JWT contains a `nonce` binding the attestation to the authenticator data, and `ctsProfileMatch` / `basicIntegrity` claims indicating the integrity state of the Android device. Reference: WebAuthn Level 2 §8.5 — Android SafetyNet Attestation Statement Format.

Miembros (3)

  • constructorAndroidSafetyNetAttestationVerifier
    public AndroidSafetyNetAttestationVerifier(IAttestationTrustStore? trustStore = null, Microsoft.Extensions.Options.IOptions<WebAuthnOptions>? options = null)

    Initializes a new instance of the `AndroidSafetyNetAttestationVerifier` class.

    trustStore: IAttestationTrustStore?
    The optional attestation trust store.
    options: Microsoft.Extensions.Options.IOptions<WebAuthnOptions>?
    The optional WebAuthn options.
  • methodVerify
    public Result Verify(AttestationStatement statement, AuthenticatorData authData, byte[] clientDataHash)

    Verifies the attestation statement against the authenticator data and client data hash.

    statement: AttestationStatement
    The parsed attestation statement.
    authData: AuthenticatorData
    The parsed authenticator data.
    clientDataHash: byte[]
    The SHA-256 hash of clientDataJSON.

    Retorna: A result indicating success or a verification error.

  • propertyFormat
    public string Format { get; }

    Gets the attestation statement format identifier ("android-safetynet").

class

FidoU2FAttestationVerifier

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed class FidoU2FAttestationVerifier : IAttestationVerifier
Implementa: IAttestationVerifier

Verifies the "fido-u2f" WebAuthn attestation statement format per §8.6 of the W3C WebAuthn Level 2 specification and the FIDO U2F Message Formats specification.

Notas:

FIDO U2F (CTAP1) attestation uses ECDSA over P-256 with the verificationData constructed as: 0x00 || rpIdHash (32) || clientDataHash (32) || credentialId || publicKeyU2F (65 bytes uncompressed). The attestation certificate public key must be an EC P-256 key.

Miembros (3)

  • constructorFidoU2FAttestationVerifier
    public FidoU2FAttestationVerifier(IAttestationTrustStore? trustStore = null, Microsoft.Extensions.Options.IOptions<WebAuthnOptions>? options = null)

    Initializes a new instance of the `FidoU2FAttestationVerifier` class.

    trustStore: IAttestationTrustStore?
    The optional attestation trust store.
    options: Microsoft.Extensions.Options.IOptions<WebAuthnOptions>?
    The optional WebAuthn options.
  • methodVerify
    public Result Verify(AttestationStatement statement, AuthenticatorData authData, byte[] clientDataHash)

    Verifies the attestation statement against the authenticator data and client data hash.

    statement: AttestationStatement
    The parsed attestation statement.
    authData: AuthenticatorData
    The parsed authenticator data.
    clientDataHash: byte[]
    The SHA-256 hash of clientDataJSON.

    Retorna: A result indicating success or a verification error.

  • propertyFormat
    public string Format { get; }

    Gets the attestation statement format identifier ("fido-u2f").

class

NoneAttestationVerifier

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed class NoneAttestationVerifier : IAttestationVerifier
Implementa: IAttestationVerifier

Verifies the "none" attestation statement format (standard for privacy-preserving authenticators and passkeys).

Miembros (3)

  • constructorNoneAttestationVerifier
    public NoneAttestationVerifier(Microsoft.Extensions.Options.IOptions<WebAuthnOptions>? options = null)

    Initializes a new instance of the `NoneAttestationVerifier` class.

    options: Microsoft.Extensions.Options.IOptions<WebAuthnOptions>?
    The optional WebAuthn options.
  • methodVerify
    public Result Verify(AttestationStatement statement, AuthenticatorData authData, byte[] clientDataHash)

    Verifies the attestation statement against the authenticator data and client data hash.

    statement: AttestationStatement
    The parsed attestation statement.
    authData: AuthenticatorData
    The parsed authenticator data.
    clientDataHash: byte[]
    The SHA-256 hash of clientDataJSON.

    Retorna: A result indicating success or a verification error.

  • propertyFormat
    public string Format { get; }

    Gets the attestation statement format identifier ("none").

class

PackedAttestationVerifier

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed class PackedAttestationVerifier : IAttestationVerifier
Implementa: IAttestationVerifier

Verifies the "packed" WebAuthn attestation statement format (supporting both self-attestation and X.509 attestation chains).

Miembros (3)

  • constructorPackedAttestationVerifier
    public PackedAttestationVerifier(IAttestationTrustStore? trustStore = null, Microsoft.Extensions.Options.IOptions<WebAuthnOptions>? options = null)

    Initializes a new instance of the `PackedAttestationVerifier` class.

    trustStore: IAttestationTrustStore?
    The optional attestation trust store.
    options: Microsoft.Extensions.Options.IOptions<WebAuthnOptions>?
    The optional WebAuthn options.
  • methodVerify
    public Result Verify(AttestationStatement statement, AuthenticatorData authData, byte[] clientDataHash)

    Verifies the attestation statement against the authenticator data and client data hash.

    statement: AttestationStatement
    The parsed attestation statement.
    authData: AuthenticatorData
    The parsed authenticator data.
    clientDataHash: byte[]
    The SHA-256 hash of clientDataJSON.

    Retorna: A result indicating success or a verification error.

  • propertyFormat
    public string Format { get; }

    Gets the attestation statement format identifier ("packed").

class

TpmAttestationVerifier

Ensamblado: EricksonLopez.Security.WebAuthn.Fido2
public sealed class TpmAttestationVerifier : IAttestationVerifier
Implementa: IAttestationVerifier

Verifies the "tpm" WebAuthn attestation statement format.

Notas:

TPM attestation uses a certInfo structure (TPMS_ATTEST) signed by a TPM Attestation Identity Key (AIK). The verification confirms: - The `certInfo` structure is of type `TPM_ST_ATTEST_CERTIFY` (0x8017). - The `extraData` field in TPMS_ATTEST equals the SHA-256 hash of the attToBeSigned (hash(authData) || clientDataHash). - The AIK certificate signature over certInfo is valid. - The AIK certificate contains the FIDO AAGUID in the Subject Alternative Name extension. Reference: WebAuthn Level 2 §8.3 — TPM Attestation Statement Format. Reference: TCG TPM Library Part 2: Structures, Section 10.12.8 TPMS_ATTEST.

Miembros (3)

  • constructorTpmAttestationVerifier
    public TpmAttestationVerifier(IAttestationTrustStore? trustStore = null, Microsoft.Extensions.Options.IOptions<WebAuthnOptions>? options = null)

    Initializes a new instance of the `TpmAttestationVerifier` class.

    trustStore: IAttestationTrustStore?
    The optional attestation trust store.
    options: Microsoft.Extensions.Options.IOptions<WebAuthnOptions>?
    The optional WebAuthn options.
  • methodVerify
    public Result Verify(AttestationStatement statement, AuthenticatorData authData, byte[] clientDataHash)

    Verifies the attestation statement against the authenticator data and client data hash.

    statement: AttestationStatement
    The parsed attestation statement.
    authData: AuthenticatorData
    The parsed authenticator data.
    clientDataHash: byte[]
    The SHA-256 hash of clientDataJSON.

    Retorna: A result indicating success or a verification error.

  • propertyFormat
    public string Format { get; }

    Gets the attestation statement format identifier ("tpm").

EricksonLopez.Security.ZeroTrust#

10
class

AbacAttributeCategory

Ensamblado: EricksonLopez.Security.ZeroTrust
public static class AbacAttributeCategory

Defines standard category constants for ABAC attributes.

Miembros (4)

  • fieldAction
    public const string Action

    Represents the attribute category for the requested action (e.g., Read, Write, Delete, Approve, Sign, Export).

  • fieldEnvironment
    public const string Environment

    Represents the attribute category for the contextual environment (e.g., RequestTime, IpAddress, DeviceTrustLevel, Location).

  • fieldResource
    public const string Resource

    Represents the attribute category for the target resource (e.g., ResourceType, ResourceId, Classification, OwnerId, Status).

  • fieldSubject
    public const string Subject

    Represents the attribute category for the requesting subject (e.g., UserId, Roles, Department, TenantId, ClearanceLevel).

enum

AbacCombiningAlgorithm

Ensamblado: EricksonLopez.Security.ZeroTrust
public enum AbacCombiningAlgorithm

Specifies the rule/policy combining algorithm for resolving multiple evaluations into a single decision.

Miembros (3)

  • fieldDenyOverrides
    DenyOverrides = 1

    Specifies that if any applicable rule evaluates to Deny, the final decision is Deny (Zero-Trust Default).

  • fieldFirstApplicable
    FirstApplicable = 3

    Specifies that rules are evaluated sequentially until the first satisfied condition determines the final decision.

  • fieldPermitOverrides
    PermitOverrides = 2

    Specifies that if any applicable rule evaluates to Permit, the final decision is Permit.

class

AbacContext

Ensamblado: EricksonLopez.Security.ZeroTrust
public sealed class AbacContext

Encapsulates the multi-dimensional contextual attributes (Subject, Resource, Action, Environment) required to evaluate ABAC security policies.

Miembros (8)

  • methodGet<T>
    public T Get<T>(string category, string name)

    Retrieves a strongly-typed attribute value, throwing an exception if not found or incompatible.

    category: string
    The category name.
    name: string
    The attribute name.

    Retorna: The attribute value cast to `T`.

    Type parameters: T: The expected type of the attribute. Exceptions: ArgumentNullException: `category` or `name` is `null`; KeyNotFoundException: The requested attribute was not found in the context

  • methodHas
    public bool Has(string category, string name)

    Determines whether an attribute exists in this context.

    category: string
    The category of the attribute to locate.
    name: string
    The name of the attribute to locate.

    Retorna: `true` if the attribute exists; otherwise, `false`.

  • methodSet
    public AbacContext Set(string category, string name, object value)

    Adds or updates an attribute in the specified category.

    category: string
    The attribute category (e.g., Subject, Resource, Action, Environment).
    name: string
    The name of the attribute.
    value: object
    The attribute value.

    Retorna: This context instance for fluent chaining.

    Exceptions: ArgumentNullException: `category`, `name`, or `value` is `null`

  • methodTryGet<T>
    public bool TryGet<T>(string category, string name, out T? value)

    Attempts to retrieve a strongly-typed attribute value.

    category: string
    The category name.
    name: string
    The attribute name.
    value: out T?
    When the operation completes, contains the value associated with the specified attribute if found; otherwise, the default value.

    Retorna: `true` if the attribute was found and matches type; otherwise, `false`.

    Type parameters: T: The expected type of the attribute. Exceptions: ArgumentNullException: `category` or `name` is `null`

  • methodWithAction
    public AbacContext WithAction(string actionName)

    Sets the Action name attribute on this evaluation context.

    actionName: string
    The name of the requested action.

    Retorna: This context instance for fluent chaining.

  • methodWithEnvironment
    public AbacContext WithEnvironment(string name, object value)

    Sets an Environment attribute on this evaluation context.

    name: string
    The name of the environment attribute.
    value: object
    The value of the environment attribute.

    Retorna: This context instance for fluent chaining.

  • methodWithResource
    public AbacContext WithResource(string name, object value)

    Sets a Resource attribute on this evaluation context.

    name: string
    The name of the resource attribute.
    value: object
    The value of the resource attribute.

    Retorna: This context instance for fluent chaining.

  • methodWithSubject
    public AbacContext WithSubject(string name, object value)

    Sets a Subject attribute on this evaluation context.

    name: string
    The name of the subject attribute.
    value: object
    The value of the subject attribute.

    Retorna: This context instance for fluent chaining.

record

AbacDecision

Ensamblado: EricksonLopez.Security.ZeroTrust
public readonly record struct AbacDecision(AbacDecisionStatus Status, string? PolicyId, string? RuleId, string? Reason)

Represents the final evaluation decision from the ABAC policy engine.

Miembros (11)

  • constructorAbacDecision
    public AbacDecision(AbacDecisionStatus Status, string? PolicyId = null, string? RuleId = null, string? Reason = null)

    Initializes a new instance of AbacDecision.

    Status: AbacDecisionStatus
    The decision status (Permit, Deny, NotApplicable, Indeterminate).
    PolicyId: string?
    The identifier of the policy that determined the decision.
    RuleId: string?
    The identifier of the specific rule that determined the decision.
    Reason: string?
    Optional human-readable diagnostic reason explaining the decision.
  • methodDeny
    public static AbacDecision Deny(string? policyId = null, string? ruleId = null, string? reason = null)

    Creates an `AbacDecision` indicating that access is explicitly denied.

    policyId: string?
    The identifier of the policy that denied access.
    ruleId: string?
    The identifier of the rule that denied access.
    reason: string?
    An optional diagnostic message explaining the decision.

    Retorna: An `AbacDecision` with status `AbacDecisionStatus.Deny`.

  • methodEnsurePermitted
    public void EnsurePermitted()

    Ensures that the decision is permitted, throwing an `UnauthorizedAccessException` otherwise. Enforces the Secure-by-Default principle to prevent Fail-Open authorization vulnerabilities (SEC-003).

    Exceptions: UnauthorizedAccessException: `IsPermitted` is `false`

  • methodIndeterminate
    public static AbacDecision Indeterminate(string? reason = null)

    Creates an `AbacDecision` indicating that an evaluation error or missing attribute occurred.

    reason: string?
    An optional diagnostic message explaining the decision.

    Retorna: An `AbacDecision` with status `AbacDecisionStatus.Indeterminate`.

  • methodNotApplicable
    public static AbacDecision NotApplicable(string? reason = null)

    Creates an `AbacDecision` indicating that no matching policy was applicable to the context.

    reason: string?
    An optional diagnostic message explaining the decision.

    Retorna: An `AbacDecision` with status `AbacDecisionStatus.NotApplicable`.

  • methodPermit
    public static AbacDecision Permit(string? policyId = null, string? ruleId = null, string? reason = null)

    Creates an `AbacDecision` indicating that access is permitted.

    policyId: string?
    The identifier of the policy that permitted access.
    ruleId: string?
    The identifier of the rule that permitted access.
    reason: string?
    An optional diagnostic message explaining the decision.

    Retorna: An `AbacDecision` with status `AbacDecisionStatus.Permit`.

  • propertyIsPermitted
    public bool IsPermitted { get; }

    Gets a value indicating whether access was permitted.

  • propertyPolicyId
    public string? PolicyId { get; init; }

    The identifier of the policy that determined the decision.

  • propertyReason
    public string? Reason { get; init; }

    Optional human-readable diagnostic reason explaining the decision.

  • propertyRuleId
    public string? RuleId { get; init; }

    The identifier of the specific rule that determined the decision.

  • propertyStatus
    public AbacDecisionStatus Status { get; init; }

    The decision status (Permit, Deny, NotApplicable, Indeterminate).

enum

AbacDecisionStatus

Ensamblado: EricksonLopez.Security.ZeroTrust
public enum AbacDecisionStatus

Represents the evaluation status result from the ABAC policy engine.

Miembros (4)

  • fieldDeny
    Deny = 2

    Specifies that access is explicitly denied.

  • fieldIndeterminate
    Indeterminate = 4

    Specifies that an error or missing required attribute prevented evaluation.

  • fieldNotApplicable
    NotApplicable = 3

    Specifies that no policies or rules matched the target evaluation context.

  • fieldPermit
    Permit = 1

    Specifies that access is permitted.

enum

AbacEffect

Ensamblado: EricksonLopez.Security.ZeroTrust
public enum AbacEffect

Specifies the intended effect when an ABAC rule condition evaluates to `true`.

Miembros (2)

  • fieldDeny
    Deny = 2

    Specifies that access is denied to the requested operation or resource.

  • fieldPermit
    Permit = 1

    Specifies that access is granted to the requested operation or resource.

class

AbacPolicy

Ensamblado: EricksonLopez.Security.ZeroTrust
public sealed class AbacPolicy

Represents an access control policy containing target criteria, combining algorithm, and a collection of rules.

Miembros (7)

  • constructorAbacPolicy
    public AbacPolicy(string policyId, IReadOnlyList<AbacRule> rules, AbacCombiningAlgorithm combiningAlgorithm = AbacCombiningAlgorithm.DenyOverrides, Func<AbacContext, bool>? target = null, string? description = null)

    Initializes a new instance of the `AbacPolicy` class.

    policyId: string
    The unique identifier of the policy.
    rules: IReadOnlyList<AbacRule>
    The ordered collection of evaluation rules contained in this policy.
    combiningAlgorithm: AbacCombiningAlgorithm
    The algorithm for resolving conflicting rule evaluation outcomes.
    target: Func<AbacContext, bool>?
    The optional predicate determining whether this policy applies to an evaluation context.
    description: string?
    The optional human-readable description of the policy.

    Exceptions: ArgumentNullException: `policyId` or `rules` is `null`

  • methodAppliesTo
    public bool AppliesTo(AbacContext context)

    Determines whether this policy applies to the specified context.

    context: AbacContext
    The attribute context to evaluate against the policy target.

    Retorna: `true` if the policy target matches or is undefined; otherwise, `false`.

    Exceptions: ArgumentNullException: `context` is `null`

  • propertyCombiningAlgorithm
    public AbacCombiningAlgorithm CombiningAlgorithm { get; }

    Gets the combining algorithm for reconciling the outcomes of the policy's rules.

  • propertyDescription
    public string? Description { get; }

    Gets the optional description of the policy.

  • propertyPolicyId
    public string PolicyId { get; }

    Gets the unique identifier of the policy.

  • propertyRules
    public IReadOnlyList<AbacRule> Rules { get; }

    Gets the list of rules evaluated by this policy.

  • propertyTarget
    public Func<AbacContext, bool>? Target { get; }

    Gets the optional target condition that determines whether this policy applies to a given context. If `null`, the policy applies to all contexts.

class

AbacPolicyEngine

Ensamblado: EricksonLopez.Security.ZeroTrust
public sealed class AbacPolicyEngine : IAbacPolicyEngine
Implementa: IAbacPolicyEngine

Provides an in-memory attribute-based access control (ABAC) policy decision point (PDP) implementation.

Miembros (3)

  • methodEvaluate
    public AbacDecision Evaluate(AbacContext context, IReadOnlyList<AbacPolicy> policies)

    Evaluates the access request context against the provided set of security policies. Returns `AbacDecisionStatus.NotApplicable` when no policy matches the context.

    context: AbacContext
    The contextual attributes of the access request.
    policies: IReadOnlyList<AbacPolicy>
    The collection of policies to evaluate.

    Retorna: The resulting access decision (Permit, Deny, NotApplicable, Indeterminate).

    Exceptions: ArgumentNullException: `context` or `policies` is `null`

  • methodEvaluateFailClosed
    public AbacDecision EvaluateFailClosed(AbacContext context, IReadOnlyList<AbacPolicy> policies)

    Evaluates policies with fail-closed semantics: if no policy applies to the request context, returns `AbacDecision.Deny(string?, string?, string?)` instead of `AbacDecisionStatus.NotApplicable`.

    context: AbacContext
    The contextual attributes of the access request.
    policies: IReadOnlyList<AbacPolicy>
    The collection of policies to evaluate.

    Retorna: `AbacDecision.Permit(string?, string?, string?)` if access is explicitly granted, `AbacDecision.Deny(string?, string?, string?)` in all other cases including no matching policy.

    SEC-003 fix: wraps `Evaluate` and converts `AbacDecisionStatus.NotApplicable` to `AbacDecision.Deny(string?, string?, string?)`. This enforces fail-closed behaviour: if no policy applies, access is denied rather than left ambiguous. Exceptions: ArgumentNullException: `context` or `policies` is `null`

  • fieldInstance
    public static readonly AbacPolicyEngine Instance

    Gets the default shared singleton instance of the `AbacPolicyEngine`.

class

AbacRule

Ensamblado: EricksonLopez.Security.ZeroTrust
public sealed class AbacRule

Represents an atomic policy rule evaluated against an `AbacContext`.

Miembros (7)

  • constructorAbacRule
    public AbacRule(string ruleId, AbacEffect effect, Func<AbacContext, bool> condition, string? description = null)

    Initializes a new instance of the `AbacRule` class.

    ruleId: string
    The unique identifier of the rule.
    effect: AbacEffect
    The authorization effect returned when the condition evaluates to `true`.
    condition: Func<AbacContext, bool>
    The predicate evaluated against the attribute context.
    description: string?
    The optional human-readable description of the rule.

    Exceptions: ArgumentNullException: `ruleId` or `condition` is `null`

  • methodDenyIf
    public static AbacRule DenyIf(string ruleId, Func<AbacContext, bool> condition, string? description = null)

    Creates a rule that yields `AbacEffect.Deny` when the condition is met.

    ruleId: string
    The unique identifier of the rule.
    condition: Func<AbacContext, bool>
    The predicate evaluated against the attribute context.
    description: string?
    The optional human-readable description of the rule.

    Retorna: A new `AbacRule` configured with the deny effect.

  • methodPermitIf
    public static AbacRule PermitIf(string ruleId, Func<AbacContext, bool> condition, string? description = null)

    Creates a rule that yields `AbacEffect.Permit` when the condition is met.

    ruleId: string
    The unique identifier of the rule.
    condition: Func<AbacContext, bool>
    The predicate evaluated against the attribute context.
    description: string?
    The optional human-readable description of the rule.

    Retorna: A new `AbacRule` configured with the permit effect.

  • propertyCondition
    public Func<AbacContext, bool> Condition { get; }

    Gets the predicate condition evaluated against the context.

  • propertyDescription
    public string? Description { get; }

    Gets the optional human-readable description of the rule.

  • propertyEffect
    public AbacEffect Effect { get; }

    Gets the effect produced if the rule condition evaluates to `true`.

  • propertyRuleId
    public string RuleId { get; }

    Gets the unique identifier of the rule.

interface

IAbacPolicyEngine

Ensamblado: EricksonLopez.Security.ZeroTrust
public interface IAbacPolicyEngine

Defines the policy decision point (PDP) for evaluating ABAC access requests.

Miembros (2)

  • methodEvaluate
    AbacDecision Evaluate(AbacContext context, IReadOnlyList<AbacPolicy> policies)

    Evaluates the access request context against the provided set of security policies. Returns `AbacDecisionStatus.NotApplicable` when no policy matches the context.

    context: AbacContext
    The contextual attributes of the access request.
    policies: IReadOnlyList<AbacPolicy>
    The collection of policies to evaluate.

    Retorna: The resulting access decision (Permit, Deny, NotApplicable, Indeterminate).

    Exceptions: ArgumentNullException: `context` or `policies` is `null`

  • methodEvaluateFailClosed
    AbacDecision EvaluateFailClosed(AbacContext context, IReadOnlyList<AbacPolicy> policies)

    Evaluates policies with fail-closed semantics: if no policy applies to the request context, returns `AbacDecision.Deny(string?, string?, string?)` instead of `AbacDecisionStatus.NotApplicable`.

    context: AbacContext
    The contextual attributes of the access request.
    policies: IReadOnlyList<AbacPolicy>
    The collection of policies to evaluate.

    Retorna: `AbacDecision.Permit(string?, string?, string?)` if access is explicitly granted, `AbacDecision.Deny(string?, string?, string?)` in all other cases including no matching policy.

    Security recommendation: Prefer `EvaluateFailClosed` over `Evaluate` in production Policy Enforcement Points (PEPs). A `AbacDecisionStatus.NotApplicable` result from `Evaluate` means no policy matched — not that access is permitted. Treating `NotApplicable` as "allowed" in the PEP creates an authorization bypass when no policy covers the request. Use `Evaluate` directly only when you explicitly need to distinguish `NotApplicable` from `Deny` for audit logging or policy debugging purposes. Exceptions: ArgumentNullException: `context` or `policies` is `null`

Microsoft.Extensions.DependencyInjection#

8
class

AspNetCoreSecurityExtensions

Ensamblado: EricksonLopez.Security.AspNetCore
public static class AspNetCoreSecurityExtensions

Provides extension methods for registering and configuring ASP.NET Core security middleware, headers, and request context services in an `IServiceCollection`.

Miembros (12)

  • methodAddApiKeySupport
    public static AuthenticationBuilder AddApiKeySupport(this AuthenticationBuilder builder, Action<ApiKeyAuthenticationOptions>? configureOptions = null)

    Configures API Key authentication using the native ASP.NET Core AuthenticationHandler.

    builder: this AuthenticationBuilder
    The authentication builder.
    configureOptions: Action<ApiKeyAuthenticationOptions>?
    An action to configure the `ApiKeyAuthenticationOptions`.

    Retorna: The original `AuthenticationBuilder` instance.

  • methodAddDPoPValidation
    public static IServiceCollection AddDPoPValidation(this IServiceCollection services, Action<DPoPValidationOptions>? configure = null)

    Registers RFC 9449 DPoP proof validation services (`IDPoPProofValidator` and bounded `InMemoryDPoPReplayStore` default).

    services: this IServiceCollection
    The service collection.
    configure: Action<DPoPValidationOptions>?
    Optional action configuring `DPoPValidationOptions`.

    Retorna: The service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`.

  • methodAddDistributedDPoPReplayStore
    public static IServiceCollection AddDistributedDPoPReplayStore(this IServiceCollection services, string keyPrefix = "", int maxLocalBarrierEntries = 100_000)

    Registers `DistributedCacheDPoPReplayStore` as the singleton `IDPoPReplayStore` backed by `IDistributedCache`.

    services: this IServiceCollection
    The service collection.
    keyPrefix: string
    Optional distributed cache key prefix (defaults to `"sec:dpop:jti:"`).
    maxLocalBarrierEntries: int
    Maximum entries in the in-process L1 anti-replay barrier (defaults to 100,000).

    Retorna: The service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`.

  • methodAddEricksonLopezIdentityPasswordHasher<TUser>
    public static IServiceCollection AddEricksonLopezIdentityPasswordHasher<TUser>(this IServiceCollection services) where TUser : class

    Registers the `Identity.IdentityPasswordHasherBridge<TUser>` as ASP.NET Core Identity's `Identity.IPasswordHasher<TUser>`.

    services: this IServiceCollection
    The service collection.

    Retorna: The service collection for chaining.

    Type parameters: TUser: The user entity type. Exceptions: ArgumentNullException: `services` is `null`

  • methodAddFailClosedTokenDenyList
    public static IServiceCollection AddFailClosedTokenDenyList(this IServiceCollection services, string tokenKeyPrefix = "", string principalKeyPrefix = "")

    Registers `DistributedCacheFailClosedTokenDenyList` as the singleton `ITokenDenyList`.

    services: this IServiceCollection
    The service collection.
    tokenKeyPrefix: string
    Optional distributed cache prefix for revoked token JTIs (defaults to `"token_deny:"`).
    principalKeyPrefix: string
    Optional distributed cache prefix for globally revoked principals (defaults to `"user_deny:"`).

    Retorna: The service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`.

  • methodAddGenerationalPermissionCache
    public static IServiceCollection AddGenerationalPermissionCache(this IServiceCollection services, Action<GenerationalPermissionCacheOptions>? configure = null)

    Registers `GenerationalPermissionCache` as `IGenerationalPermissionCache` using a pre-registered `IPermissionSnapshotSource`.

    services: this IServiceCollection
    The service collection.
    configure: Action<GenerationalPermissionCacheOptions>?
    Optional action configuring `GenerationalPermissionCacheOptions`.

    Retorna: The service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`.

  • methodAddGenerationalPermissionCache<TSource>
    public static IServiceCollection AddGenerationalPermissionCache<TSource>(this IServiceCollection services, Action<GenerationalPermissionCacheOptions>? configure = null) where TSource : class, IPermissionSnapshotSource

    Registers `TSource` as `IPermissionSnapshotSource` along with `GenerationalPermissionCache`.

    services: this IServiceCollection
    The service collection.
    configure: Action<GenerationalPermissionCacheOptions>?
    Optional action configuring `GenerationalPermissionCacheOptions`.

    Retorna: The service collection for chaining.

    Type parameters: TSource: The authoritative `IPermissionSnapshotSource` implementation. Exceptions: ArgumentNullException: `services` is `null`.

  • methodAddSecurityAspNetCore
    public static IServiceCollection AddSecurityAspNetCore(this IServiceCollection services, Action<SecurityHeadersOptions>? configureHeaders = null, Action<ApiKeyAuthenticationOptions>? configureApiKeyAuth = null)

    Registers ASP.NET Core security services including headers options, API key authentication options, and scoped `IRequestSecurityContext`.

    services: this IServiceCollection
    The service collection.
    configureHeaders: Action<SecurityHeadersOptions>?
    Optional action to configure security headers.
    configureApiKeyAuth: Action<ApiKeyAuthenticationOptions>?
    Optional action to configure API key authentication.

    Retorna: The service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`

  • methodAddZeroTrustMultiPlaneAuthorization
    public static IServiceCollection AddZeroTrustMultiPlaneAuthorization(this IServiceCollection services, Action<SafeAuthorizationResultHandlerOptions>? configureResultHandler = null)

    Registers Zero-Trust multi-plane authorization handlers (`TokenUseAuthorizationHandler`, `SecurityPlaneAuthorizationHandler`, `AssuranceLevelAuthorizationHandler`) and `SafeMultiSchemeAuthorizationResultHandler`.

    services: this IServiceCollection
    The service collection.
    configureResultHandler: Action<SafeAuthorizationResultHandlerOptions>?
    Optional action configuring `SafeAuthorizationResultHandlerOptions`.

    Retorna: The service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`.

  • methodUseApiKeyAuthentication
    public static IApplicationBuilder UseApiKeyAuthentication(this IApplicationBuilder app)

    Adds `ApiKeyAuthenticationMiddleware` to the application request pipeline.

    app: this IApplicationBuilder
    The application builder.

    Retorna: The application builder for chaining.

    Exceptions: ArgumentNullException: `app` is `null`

  • methodUseDPoPValidation
    public static IApplicationBuilder UseDPoPValidation(this IApplicationBuilder app)

    Adds `DPoPProofValidationMiddleware` to the ASP.NET Core request pipeline. Place after `UseAuthentication()` and before `UseAuthorization()` or endpoint execution.

    app: this IApplicationBuilder
    The application builder.

    Retorna: The application builder for chaining.

    Exceptions: ArgumentNullException: `app` is `null`.

  • methodUseSecurityHeaders
    public static IApplicationBuilder UseSecurityHeaders(this IApplicationBuilder app)

    Adds `SecurityHeadersMiddleware` to the application request pipeline.

    app: this IApplicationBuilder
    The application builder.

    Retorna: The application builder for chaining.

    Exceptions: ArgumentNullException: `app` is `null`

class

AwsSecurityExtensions

Ensamblado: EricksonLopez.Security.Aws
public static class AwsSecurityExtensions

Provides extension methods for registering AWS KMS key store and AWS Secrets Manager secret store adapters in an `IServiceCollection`.

Miembros (2)

  • methodAddAwsSecurity
    public static IServiceCollection AddAwsSecurity(this IServiceCollection services)

    Registers AWS KMS key store and AWS Secrets Manager secret store adapters with default options.

    services: this IServiceCollection
    The service collection to register the adapters into.

    Retorna: The configured `IServiceCollection` instance.

    Exceptions: ArgumentNullException: `services` is `null`

  • methodAddAwsSecurity
    public static IServiceCollection AddAwsSecurity(this IServiceCollection services, Action<AwsSecurityOptions> configure)

    Registers AWS KMS key store and AWS Secrets Manager secret store adapters.

    services: this IServiceCollection
    The service collection to register the adapters into.
    configure: Action<AwsSecurityOptions>
    The configuration delegate for AWS security options.

    Retorna: The configured `IServiceCollection` instance.

    Exceptions: ArgumentNullException: `services` or `configure` is `null`

class

AzureKeyVaultSecurityExtensions

Ensamblado: EricksonLopez.Security.Azure
public static class AzureKeyVaultSecurityExtensions

Provides extension methods for registering Azure Key Vault key and secret store adapters in an `IServiceCollection`.

Miembros (2)

  • methodAddAzureKeyVaultSecurity
    public static IServiceCollection AddAzureKeyVaultSecurity(this IServiceCollection services)

    Registers Azure Key Vault key store and secret store adapters with default options.

    services: this IServiceCollection
    The service collection to register the adapters into.

    Retorna: The configured `IServiceCollection` instance.

    Exceptions: ArgumentNullException: `services` is `null`

  • methodAddAzureKeyVaultSecurity
    public static IServiceCollection AddAzureKeyVaultSecurity(this IServiceCollection services, Action<AzureKeyVaultOptions> configure)

    Registers Azure Key Vault key store and secret store adapters.

    services: this IServiceCollection
    The service collection to register the adapters into.
    configure: Action<AzureKeyVaultOptions>
    The configuration delegate for Azure Key Vault options.

    Retorna: The configured `IServiceCollection` instance.

    Exceptions: ArgumentNullException: `services` or `configure` is `null`

class

CryptographyServiceCollectionExtensions

Ensamblado: EricksonLopez.Security.Cryptography
public static class CryptographyServiceCollectionExtensions

Provides extension methods for registering cryptographic services in an `IServiceCollection`.

Miembros (2)

  • methodAddBoundedArgon2PasswordHasher
    public static IServiceCollection AddBoundedArgon2PasswordHasher(this IServiceCollection services, System.Action<BoundedPasswordHasherOptions>? configure = null)

    Registers a concurrency-bounded `BoundedPasswordHasher` wrapping `Argon2idPasswordHasher`.

    services: this IServiceCollection
    The service collection.
    configure: System.Action<BoundedPasswordHasherOptions>?
    Optional callback to configure `BoundedPasswordHasherOptions`.

    Retorna: The configured `IServiceCollection`.

  • methodAddEricksonLopezCryptographyCore
    public static IServiceCollection AddEricksonLopezCryptographyCore(this IServiceCollection services)

    Registers the core cryptography primitives (RNG, ConstantTimeComparer, AEAD AES-GCM, and PBKDF2 PasswordHasher) as singletons.

    services: this IServiceCollection
    The service collection to register cryptographic services into.

    Retorna: The configured `IServiceCollection` instance.

class

GoogleCloudSecurityExtensions

Ensamblado: EricksonLopez.Security.GoogleCloud
public static class GoogleCloudSecurityExtensions

Provides extension methods for registering Google Cloud KMS and Secret Manager key and secret store adapters in an `IServiceCollection`.

Miembros (3)

  • methodAddGoogleCloudKmsKeyWrapping
    public static IServiceCollection AddGoogleCloudKmsKeyWrapping(this IServiceCollection services, Action<GoogleCloudSecurityOptions>? configure = null)

    Registers `GoogleCloudKmsKeyWrappingProvider` as the singleton `IKmsKeyWrappingProvider`.

    services: this IServiceCollection
    The service collection.
    configure: Action<GoogleCloudSecurityOptions>?
    Optional configuration delegate for `GoogleCloudSecurityOptions`.

    Retorna: The configured `IServiceCollection` instance.

    Exceptions: ArgumentNullException: `services` is `null`.

  • methodAddGoogleCloudSecurity
    public static IServiceCollection AddGoogleCloudSecurity(this IServiceCollection services)

    Registers Google Cloud KMS and Secret Manager adapters with default options.

    services: this IServiceCollection
    The service collection to register the adapters into.

    Retorna: The configured `IServiceCollection` instance.

    Exceptions: ArgumentNullException: `services` is `null`

  • methodAddGoogleCloudSecurity
    public static IServiceCollection AddGoogleCloudSecurity(this IServiceCollection services, Action<GoogleCloudSecurityOptions> configure)

    Registers Google Cloud KMS and Secret Manager adapters.

    services: this IServiceCollection
    The service collection to register the adapters into.
    configure: Action<GoogleCloudSecurityOptions>
    The configuration delegate for Google Cloud security options.

    Retorna: The configured `IServiceCollection` instance.

    Exceptions: ArgumentNullException: `services` or `configure` is `null`

class

HashiCorpVaultSecurityExtensions

Ensamblado: EricksonLopez.Security.HashiCorpVault
public static class HashiCorpVaultSecurityExtensions

Provides extension methods for registering HashiCorp Vault key and secret store adapters in an `IServiceCollection`.

Miembros (2)

  • methodAddHashiCorpVaultSecurity
    public static IServiceCollection AddHashiCorpVaultSecurity(this IServiceCollection services)

    Registers HashiCorp Vault Transit key store and KV v2 secret store adapters with default options.

    services: this IServiceCollection
    The service collection to register the adapters into.

    Retorna: The configured `IServiceCollection` instance.

    Exceptions: ArgumentNullException: `services` is `null`

  • methodAddHashiCorpVaultSecurity
    public static IServiceCollection AddHashiCorpVaultSecurity(this IServiceCollection services, Action<HashiCorpVaultOptions> configure)

    Registers HashiCorp Vault Transit key store and KV v2 secret store adapters.

    services: this IServiceCollection
    The service collection to register the adapters into.
    configure: Action<HashiCorpVaultOptions>
    The configuration delegate for HashiCorp Vault options.

    Retorna: The configured `IServiceCollection` instance.

    Exceptions: ArgumentNullException: `services` or `configure` is `null`

class

Pkcs11ServiceCollectionExtensions

Ensamblado: EricksonLopez.Security.Cryptography.Pkcs11
public static class Pkcs11ServiceCollectionExtensions

Provides extension methods for registering PKCS#11 hardware security module (HSM) services in an `IServiceCollection`.

Miembros (1)

  • methodAddEricksonLopezPkcs11
    public static IServiceCollection AddEricksonLopezPkcs11(this IServiceCollection services, string libraryPath, uint slotId)

    Registers PKCS#11 native library and session manager components into the service collection.

    services: this IServiceCollection
    The service collection to configure.
    libraryPath: string
    The absolute path to the native PKCS#11 shared library.
    slotId: uint
    The cryptographic slot identifier to open a session on.

    Retorna: The configured `IServiceCollection` instance.

    Exceptions: ArgumentNullException: `services` is `null`; ArgumentException: `libraryPath` is `null` or white-space; InvalidOperationException: The PKCS#11 session initialization fails when resolved from the service provider

class

SecurityServiceCollectionExtensions

Ensamblado: EricksonLopez.Security
public static class SecurityServiceCollectionExtensions

Provides extension methods for registering `EricksonLopez.Security` services, cryptographic engines, key managers, password hashers, token generators, and secret protectors in the dependency injection container.

Miembros (13)

  • methodAddDistributedKeyRevocationNotifier
    public static IServiceCollection AddDistributedKeyRevocationNotifier(this IServiceCollection services, Func<EricksonLopez.Security.Abstractions.Primitives.KeyIdentifier, EricksonLopez.Security.Abstractions.Primitives.KeyVersion, EricksonLopez.Security.Abstractions.Primitives.KeyPurpose, System.Threading.CancellationToken, System.Threading.Tasks.ValueTask> publishHandler)

    Registers a distributed key revocation notifier using a custom asynchronous dispatch delegate (e.g., Redis Pub/Sub, RabbitMQ, Kafka).

    services: this IServiceCollection
    The service collection.
    publishHandler: Func<EricksonLopez.Security.Abstractions.Primitives.KeyIdentifier, EricksonLopez.Security.Abstractions.Primitives.KeyVersion, EricksonLopez.Security.Abstractions.Primitives.KeyPurpose, System.Threading.CancellationToken, System.Threading.Tasks.ValueTask>
    The delegate invoked to broadcast revocation events to an external message broker.

    Retorna: The service collection for chaining.

    Exceptions: ArgumentNullException: `services` or `publishHandler` is `null`

  • methodAddDistributedKeyRevocationNotifier
    public static IServiceCollection AddDistributedKeyRevocationNotifier(this IServiceCollection services, Func<IServiceProvider, Func<EricksonLopez.Security.Abstractions.Primitives.KeyIdentifier, EricksonLopez.Security.Abstractions.Primitives.KeyVersion, EricksonLopez.Security.Abstractions.Primitives.KeyPurpose, System.Threading.CancellationToken, System.Threading.Tasks.ValueTask>> publishHandlerFactory)

    Registers a distributed key revocation notifier using a service-provider-resolved asynchronous dispatch delegate.

    services: this IServiceCollection
    The service collection.
    publishHandlerFactory: Func<IServiceProvider, Func<EricksonLopez.Security.Abstractions.Primitives.KeyIdentifier, EricksonLopez.Security.Abstractions.Primitives.KeyVersion, EricksonLopez.Security.Abstractions.Primitives.KeyPurpose, System.Threading.CancellationToken, System.Threading.Tasks.ValueTask>>
    The factory function that resolves the publish delegate from the service provider.

    Retorna: The service collection for chaining.

    Exceptions: ArgumentNullException: `services` or `publishHandlerFactory` is `null`

  • methodAddEricksonLopezSecurity
    public static IServiceCollection AddEricksonLopezSecurity(this IServiceCollection services)

    Registers the complete suite of `EricksonLopez.Security` services in one call.

    services: this IServiceCollection
    The service collection.

    Retorna: The service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`

  • methodAddKeyManagement
    public static IServiceCollection AddKeyManagement(this IServiceCollection services)

    Registers key management infrastructure: in-memory key store (default), key ring, and key lifecycle manager.

    services: this IServiceCollection
    The service collection.

    Retorna: The service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`

  • methodAddLocalKmsKeyWrapping
    public static IServiceCollection AddLocalKmsKeyWrapping(this IServiceCollection services, ReadOnlySpan<byte> keyEncryptionKey, bool requireAssociatedData = false)

    Registers `LocalAesGcmKmsKeyWrappingProvider` as the singleton `IKmsKeyWrappingProvider` using the supplied 256-bit Key Encryption Key (KEK).

    services: this IServiceCollection
    The service collection.
    keyEncryptionKey: ReadOnlySpan<byte>
    The 32-byte (256-bit) KEK material.
    requireAssociatedData: bool
    When `true`, empty AAD is rejected fail-closed.

    Retorna: The service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`.; ArgumentException: `keyEncryptionKey` is not 32 bytes.

  • methodAddPasswordSecurity
    public static IServiceCollection AddPasswordSecurity(this IServiceCollection services, int iterations = Pbkdf2PasswordHasher.DefaultIterations)

    Registers modern password security hashing infrastructure (PBKDF2-HMAC-SHA512 default with Argon2id support).

    services: this IServiceCollection
    The service collection.
    iterations: int
    Optional iterations count for PBKDF2 (defaults to 210,000).

    Retorna: The service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`

  • methodAddRsaKeyEnvelopeProtector
    public static IServiceCollection AddRsaKeyEnvelopeProtector(this IServiceCollection services, string aadDomainPrefix = "")

    Registers `RsaKeyEnvelopeProtector` for KMS-wrapped PKCS#8 RSA key generation, rotation, and unwrapping.

    services: this IServiceCollection
    The service collection.
    aadDomainPrefix: string
    Optional domain-separation prefix bound into `kid` AAD.

    Retorna: The service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`.

  • methodAddRsaKeyRing
    public static IServiceCollection AddRsaKeyRing(this IServiceCollection services, Func<IServiceProvider, IRsaKeyRing> factory)

    Registers a singleton `IRsaKeyRing` instance constructed by `factory`.

    services: this IServiceCollection
    The service collection.
    factory: Func<IServiceProvider, IRsaKeyRing>
    Factory resolving the in-memory `IRsaKeyRing`.

    Retorna: The service collection for chaining.

    Exceptions: ArgumentNullException: `services` or `factory` is `null`.

  • methodAddSecretProtection
    public static IServiceCollection AddSecretProtection(this IServiceCollection services)

    Registers envelope-based secret protection and secret resolution infrastructure.

    services: this IServiceCollection
    The service collection.

    Retorna: The service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`

  • methodAddSecurityCore
    public static IServiceCollection AddSecurityCore(this IServiceCollection services)

    Registers core security primitives, CSPRNG randomness, constant-time comparers, and envelope serializers.

    services: this IServiceCollection
    The service collection.

    Retorna: The service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`

  • methodAddTokenSecurity
    public static IServiceCollection AddTokenSecurity(this IServiceCollection services, byte[]? pepperKey = null)

    Registers token security infrastructure: opaque token generators, HMAC token hashers, and API key generators.

    services: this IServiceCollection
    The service collection.
    pepperKey: byte[]?
    Optional application-level pepper key bytes for HMAC-SHA256 hashing.

    Retorna: The service collection for chaining.

    Exceptions: ArgumentNullException: `services` is `null`; ArgumentOutOfRangeException: `pepperKey` is not null, non-empty, and less than 32 bytes in length

  • methodAddVersionedCredentialHmac
    public static IServiceCollection AddVersionedCredentialHmac(this IServiceCollection services, Action<VersionedCredentialHmacOptions> configure)

    Registers `IVersionedCredentialHmacService` (`VersionedCredentialHmacService`) and `IServiceCredentialEvaluator` (`ServiceCredentialEvaluator`) for domain-separated HMAC-SHA256 backup codes, refresh tokens, and M2M service credentials with grace-window and CIDR enforcement.

    services: this IServiceCollection
    The service collection.
    configure: Action<VersionedCredentialHmacOptions>
    Action configuring `VersionedCredentialHmacOptions`.

    Retorna: The service collection for chaining.

    Exceptions: ArgumentNullException: `services` or `configure` is `null`.

  • methodAddVersionedSecretProtection
    public static IServiceCollection AddVersionedSecretProtection(this IServiceCollection services, Action<VersionedSecretProtectorOptions> configure)

    Registers `IVersionedSecretProtector` (`VersionedAesGcmSecretProtector`) for compact `v1.<base64url>` AES-256-GCM secret protection with external contextual AAD and HKDF key-version derivation.

    services: this IServiceCollection
    The service collection.
    configure: Action<VersionedSecretProtectorOptions>
    Action configuring `VersionedSecretProtectorOptions`.

    Retorna: The service collection for chaining.

    Exceptions: ArgumentNullException: `services` or `configure` is `null`.

Buscar en el Ecosistema EricksonLopez.*

Escribe el nombre de una librería, ID de paquete NuGet, tipo .NET o concepto arquitectónico para buscar en el portal.