Bouncy Castle Cryptography for .NET

repository·master·Indexed 23 days ago

https://github.com/bcgit/bc-csharp

A comprehensive .NET implementation of cryptographic algorithms and protocols, including CMS, OpenPGP, and TLS. It provides extensive support for symmetric and asymmetric key algorithms, AEAD block cipher modes, digests, and X.509 certificates. The library also includes experimental support for NIST Post-Quantum Cryptography algorithms such as ML-DSA and ML-KEM. Distributed via NuGet as BouncyCastle.Cryptography, it offers hardware acceleration for AES and Span-based APIs for .NET 6.0.

Tokens
4.4K
Snippets
1
Records
24
Agent score
82%

What's inside Bouncy Castle Cryptography for .NET

  1. Overview of Bouncy Castle Cryptography for .NET

    master

    Bouncy Castle is a .NET implementation of cryptographic algorithms and protocols. It provides support for:

    • Basic Cryptography: Standard cryptographic algorithms.
    • Protocols & Standards: CMS, OpenPGP, (D)TLS, TSP, and X.509 certificate generation.
    • Post-Quantum Cryptography (Experimental): NIST Post-Quantum Cryptography Standardization algorithms including ML-DSA, ML-KEM, SLH-DSA, Falcon, Classic McEliece, FrodoKEM, NTRU, NTRU Prime, Picnic, Saber, and BIKE. Note that these are considered EXPERIMENTAL and are subject to change or removal.

    Important Note: This repository contains the standard APIs. If you require the FIPS version of the APIs, you must visit the specific FIPS project page or contact Bouncy Castle directly.

  2. Understand the design and scope of Org.BouncyCastle.Math.BinPoly

    master

    The Org.BouncyCastle.Math.BinPoly namespace provides a high-performance, unified implementation of binary-polynomial (GF(2)[x]) arithmetic. It is designed to replace ad-hoc implementations used in various parts of the Bouncy Castle library (like F2mFieldElement, BikeRing, and Hqc.GF2x) with a single, well-tested core.

    Key Capabilities

    • Arithmetic Operations: Multiplication, squaring, and repeated squaring (SquareN), all producing fully reduced results.
    • Modular Reduction: Supports reduction by binomial ($x^n + 1$), trinomial ($x^n + x^k + 1$), and pentanomial ($x^n + x^{k3} + x^{k2} + x^{k1} + 1$) polynomials.
    • Inversion: Supports inversion in $GF(2^n)$ using the Itoh–Tsujii algorithm (for field/irreducible moduli).
    • Flexibility: Supports any degree $n$ (even or odd, including multiples of 64).
    • Performance: Utilizes two backends: an x86 Vector128 PCLMULQDQ backend for hardware acceleration and a portable scalar fallback.

    Data Representation

    Polynomials are bit-packed in ulong[] using little-endian word order. Bit $i$ of the polynomial is stored at bit ($i$ mod 64) of limb ($i$ / 64).

  3. Thread Safety and Memory Management in BinPoly

    master

    The IBinPolyMul instances are designed to be thread-safe and can be shared across multiple threads.

    Scratch Memory Handling

    To maintain thread safety and performance, the library avoids storing state on the instance. Instead, scratch memory is managed as follows:

    • Small/Mid-sized (V128): Uses stackalloc for the extended product buffer.
    • Large sizes: Rents a combined tt + scratch buffer from a private ArrayPool<ulong>. This pool is created via ArrayPool.Create (not the shared system pool) to ensure secret partial products are isolated and wiped upon release.
    • Threading: All scratch memory is threaded through recursion as a parameter rather than being stored as an instance field.
  4. Understand the BinPoly multiplication dispatch logic

    master

    Multiplication performance is optimized by dispatching to specialized, sealed implementations based on the operand size (number of ulong limbs) and the available Instruction Set Architecture (ISA).

    X86.V128 Backend (Hardware Accelerated)

    Uses PCLMULQDQ via Vector128<ulong>. The KaratsubaCutoff is 32 limbs.

    Size (limbs)ImplementationLeaf Kernel
    1 – 10Size1 ... Size10fully-unrolled ImplMul1 ... ImplMul10
    11 – 31MediumOdd / MediumEvensingle-level Karatsuba ImplMulOdd / ImplMulEven
    ≥ 32Largerecursive Karatsuba → ImplMulEven / ImplMulOdd leaf

    Scalar Backend (Portable Fallback)

    Used on platforms without hardware support or when intrinsics are disabled. The KaratsubaCutoff is 8 limbs.

    Size (limbs)ImplementationLeaf Kernel
    1 – 7Mediumtable schoolbook ImplMul
    ≥ 8Largerecursive Karatsuba → ImplMul leaf
  5. How the BinPoly architecture works

    master

    The BinPoly architecture is layered to balance high-level ease of use with low-level performance. It uses a facade pattern to hide complex implementation details behind narrow interfaces.

    Architectural Layers

    1. BinPolys (Static Facade): The primary entry point. It provides reducer-independent helpers (like Size, Create, Copy, Clear) and nested factory classes (Mul and Inv) to instantiate arithmetic engines.
    2. IBinPolyMul & IBinPolyInv (Interfaces): Narrow, array-based interfaces that consumers interact with. IBinPolyMul provides Multiply, Square, and SquareN. IBinPolyInv provides Invert.
    3. BinPolyMulBase (Abstract Base): Implements the shared logic for Square and SquareN and manages the internal state, including the reduction strategy (IReduce).
    4. Sealed Implementations: Specific, highly optimized classes (e.g., V128Impls, ScalarImpls) are selected based on the operand size and the available Instruction Set Architecture (ISA). These are designed to be devirtualized and inlined by the JIT compiler.
    5. Backends & Kernels: The Backend layer acts as a factory and availability gate (e.g., checking if x86 Vector128 is enabled), while Kernels provide the raw carry-less-multiply routines.
  6. Security and Side-Channel Considerations in BinPoly

    master

    The BinPoly design follows a strict constant-time discipline to protect against side-channel attacks:

    • Branching: The library only branches on non-secret parameters (such as the polynomial degree n or the tap positions k). It never branches on the actual element data.
    • Hardware Path: The X86.V128 backend is designed to be constant-time.
    • Scalar Fallback Warning: The Scalar fallback uses a 16-entry table indexed by 4 bits of an operand. This introduces a cache-timing side channel. For deployments requiring protection against cache-timing attackers, ensure the hardware-accelerated path (PCLMULQDQ) is available and enabled.
    • Memory Wiping: Secret intermediate buffers are wiped using BinPolys.Clear, which utilizes CryptographicOperations.ZeroMemory to prevent JIT elision.
    • Responsibility: When using IReduce, the caller is responsible for wiping the extended buffer tt after use, as its post-reduction contents are arbitrary.
  7. Use BinPolys factories for multiplication and inversion

    master

    The Org.BouncyCastle.Math.BinPoly namespace provides a high-level factory API for performing arithmetic on binary polynomials. You should interact with the BinPolys factory rather than managing backends or reducers manually.

    Multiplication

    Use BinPolys.Mul to obtain an IBinPolyMul instance. The factory automatically selects the most efficient backend (e.g., X86.V128 with PCLMULQDQ if available, or a portable Scalar fallback) and the appropriate reducer based on the polynomial parameters (binomial, trinomial, or pentanomial).

    Inversion

    Use BinPolys.Inv.ItohTsujii to obtain an IBinPolyInv instance. This implementation is backend-independent and uses the Itoh–Tsujii identity.

    Note: Inversion is only mathematically correct for irreducible reduction polynomials (fields). The library enforces this by only allowing trinomial and pentanomial factories to be routed to the Inv factory; binomial rings are excluded.

  8. Get support and provide feedback for Bouncy Castle

    master

    For usage questions, enhancement requests, or general discussions, use the GitHub Discussions page. The former dev-crypto-csharp mailing list has been discontinued.

    • Bug Reports: Report issues on GitHub or via feedback-crypto@bouncycastle.org.
    • Direct Feedback: Contact the Legion directly at feedback-crypto@bouncycastle.org.
    • Release Announcements: Subscribe to announce-crypto-csharp-request@bouncycastle.org (include 'subscribe' in the message body) to receive new release notifications.
  9. Overview of Bouncy Castle C# Cryptographic API

    master
    The Bouncy Castle C# API is a comprehensive cryptographic library for .NET. It is a port of the Bouncy Castle Java APIs, maintaining approximately 80% of the Java functionality while adopting .NET naming conventions. It provides a wide range of cryptographic transformations, including symmetric and asymmetric algorithms, digital signatures, key agreement, and protocol implementations like TLS/DTLS and OpenPGP.
  10. Release history of Bouncy Castle C#

    master

    The Bouncy Castle Cryptography Library for .NET has a long history of releases. Key milestones include:

    • v1.7 (2011-04-07): Added TLS client authentication, compression, and ECC cipher suites (RFC 4492). Added ASN.1 classes for CRMF and CMP.
    • v1.6 (2010-02-04): Added CMS support for PSS signatures, improved GCM mode performance (10x), and extended raw signature support to RSA, RSA-PSS, and ECDSA.
    • v1.5 (2009-08-18): Added PKIX certificate path validation, PKCS#5 Scheme 2 key support, and SRP-6a protocol support.
    • v1.4 (2008-08-08): Added Galois/Counter Mode (GCM) and new Pkcs12StoreBuilder for 3DES protected files.
    • v1.0 (2007-01-18): Initial release providing CMS, OCSP, OpenPGP, TSP, Elliptic Curves, and a basic TLS client.