# `ExCEP.Crypto.Cert`

Pure-Elixir **SM2 X.509 Certificate & Key Parser/Encoder** (GM/T 0015, GB/T 32918, RFC 5280).

Supports parsing and generating standard Chinese National Cryptography (国密 SM2/SM3)
certificates and key files in both **PEM** (`.pem`, `.crt`, `.cer`, `.key`, `.pub`) and
raw **ASN.1 DER** formats, with zero external NIF dependencies.

## Supported Formats
- **X.509 Certificates** (`CERTIFICATE` PEM / DER):
  - Extracts SM2 public key (uncompressed `04||X||Y` or compressed `02/03||X`) as 64-byte raw `<<X::256, Y::256>>`
  - Validates curve OID (`sm2p256v1` = `1.2.156.10197.1.301`) and on-curve coordinates
  - Extracts `version`, `serial_number`, `subject`, `issuer`, `not_before`, `not_after`, `signature_algorithm`, `tbs_der`, `signature`
  - Verifies SM2-with-SM3 (`1.2.156.10197.1.501`) certificate signatures via `verify_cert/3`
- **Private Keys** (PEM / DER):
  - PKCS#8 `PRIVATE KEY` (`PrivateKeyInfo` wrapping SM2 `ECPrivateKey`)
  - SEC1 `EC PRIVATE KEY` / `SM2 PRIVATE KEY`
  - Raw 32-byte binary or 64-character hex string
- **Public Keys** (PEM / DER):
  - SPKI `PUBLIC KEY` (`SubjectPublicKeyInfo` with `sm2p256v1`)
  - X.509 `CERTIFICATE`
  - Raw 64/65-byte uncompressed or 33-byte compressed binary, or hex string

## Quick Example

    {:ok, signer} =
      ExCEP.Crypto.Cert.build_signer(
        private_key_file: "/etc/cep/gateway.key",
        cert_file: "/etc/cep/gateway.crt",
        peer_cert_file: "/etc/cep/cluster.crt"
      )

    # Pass directly to ExCEP.start_gateway(..., signer: signer)

# `t`

```elixir
@type t() :: %ExCEP.Crypto.Cert{
  curve_oid: tuple(),
  der: binary(),
  issuer: %{required(String.t()) =&gt; String.t()},
  not_after: DateTime.t(),
  not_before: DateTime.t(),
  public_key: &lt;&lt;_::512&gt;&gt;,
  serial_number: non_neg_integer(),
  signature: binary(),
  signature_algorithm: tuple(),
  subject: %{required(String.t()) =&gt; String.t()},
  tbs_der: binary(),
  version: 1 | 2 | 3
}
```

# `build_signer`

```elixir
@spec build_signer(keyword()) :: {:ok, {module(), keyword()}} | {:error, term()}
```

Builds a ready-to-use `{ExCEP.Crypto.SM2, opts}` signer tuple from certificate/key files,
PEM/DER binaries, or raw keys.

All files and PEMs are decoded once upfront so signing/verifying incurs zero disk/ASN.1 overhead.

## Options
- `:private_key` | `:private_key_pem` | `:private_key_file` - local SM2 private key
- `:public_key` | `:public_key_pem` | `:public_key_file` | `:cert` | `:cert_pem` | `:cert_file` - local SM2 public key/cert (optional; derived from private key if omitted)
- `:peer_public_key` | `:peer_public_key_pem` | `:peer_public_key_file` | `:peer_cert` | `:peer_cert_pem` | `:peer_cert_file` - remote peer SM2 public key/cert
- `:ca_cert` | `:ca_cert_pem` | `:ca_cert_file` - optional CA cert; if provided together with a peer cert, verifies the peer cert signature and validity period before accepting it
- `:user_id` - SM2 user ID (default `"1234567812345678"`)

# `encode_cert_pem`

```elixir
@spec encode_cert_pem(t() | binary()) :: binary()
```

Encodes a `%ExCEP.Crypto.Cert{}` or raw DER binary as `CERTIFICATE` PEM.

# `encode_ec_private_key_pem`

```elixir
@spec encode_ec_private_key_pem(&lt;&lt;_::256&gt;&gt;, keyword()) :: binary()
```

Encodes a 32-byte SM2 private key as SEC1 `EC PRIVATE KEY` PEM.

# `encode_private_key_pem`

```elixir
@spec encode_private_key_pem(&lt;&lt;_::256&gt;&gt;, keyword()) :: binary()
```

Encodes a 32-byte SM2 private key as PKCS#8 `PRIVATE KEY` PEM.

# `encode_public_key_pem`

```elixir
@spec encode_public_key_pem(binary()) :: binary()
```

Encodes a 64- or 65-byte SM2 public key as SPKI `PUBLIC KEY` PEM.

# `generate_cert`

```elixir
@spec generate_cert(&lt;&lt;_::256&gt;&gt;, keyword()) :: {:ok, t(), binary()} | {:error, term()}
```

Generates a standards-compliant SM2-with-SM3 X.509 v3 certificate (self-signed or CA-signed).

Returns `{:ok, %ExCEP.Crypto.Cert{}, pem_binary}`.

## Options
- `:subject` - map of RDN fields, e.g. `%{"CN" => "gw-01", "O" => "CSG"}` (default `%{"CN" => "ExCEP"}`)
- `:issuer` - map of issuer RDN fields (defaults to `:subject`)
- `:issuer_private_key` - 32-byte CA private key to sign with (defaults to `subject_private_key`)
- `:serial_number` - positive integer (default random 64-bit positive integer)
- `:not_before` - `DateTime.t()` (default `DateTime.utc_now/0`)
- `:not_after` - `DateTime.t()` (default 365 days after `not_before`)
- `:user_id` - SM2 user ID (default `"1234567812345678"`)

# `parse_cert`

```elixir
@spec parse_cert(binary()) :: {:ok, t()} | {:error, term()}
```

Parses an SM2 X.509 certificate from a PEM string or raw DER binary.

# `parse_cert_file`

```elixir
@spec parse_cert_file(Path.t()) :: {:ok, t()} | {:error, term()}
```

Loads and parses an SM2 X.509 certificate from a PEM or DER file.

# `parse_private_key`

```elixir
@spec parse_private_key(binary()) :: {:ok, &lt;&lt;_::256&gt;&gt;} | {:error, term()}
```

Parses an SM2 private key into a 32-byte raw big-endian scalar.

Accepts:
- Raw 32-byte binary
- 64-character hex string (with optional whitespace)
- PEM or DER PKCS#8 `PRIVATE KEY`
- PEM or DER SEC1 `EC PRIVATE KEY` / `SM2 PRIVATE KEY`

# `parse_private_key_file`

```elixir
@spec parse_private_key_file(Path.t()) :: {:ok, &lt;&lt;_::256&gt;&gt;} | {:error, term()}
```

Loads and parses an SM2 private key from a PEM, DER, raw, or hex file.

# `parse_public_key`

```elixir
@spec parse_public_key(t() | binary()) :: {:ok, &lt;&lt;_::512&gt;&gt;} | {:error, term()}
```

Parses an SM2 public key into a 64-byte raw uncompressed binary `<<X::256, Y::256>>`.

Accepts:
- `%ExCEP.Crypto.Cert{}`
- Raw 64-byte (`X||Y`), 65-byte (`04||X||Y`), or 33-byte compressed (`02/03||X`) binary
- Hex-encoded 64/65/33-byte public key string
- PEM or DER `PUBLIC KEY` (SubjectPublicKeyInfo)
- PEM or DER `CERTIFICATE` (X.509)

# `parse_public_key_file`

```elixir
@spec parse_public_key_file(Path.t()) :: {:ok, &lt;&lt;_::512&gt;&gt;} | {:error, term()}
```

Loads and parses an SM2 public key (or certificate) from a file into a 64-byte raw key.

# `sm2_curve_oid`

```elixir
@spec sm2_curve_oid() :: tuple()
```

Returns the `sm2p256v1` curve OID `{1, 2, 156, 10197, 1, 301}`.

# `sm2_with_sm3_oid`

```elixir
@spec sm2_with_sm3_oid() :: tuple()
```

Returns the `SM2-with-SM3` signature algorithm OID `{1, 2, 156, 10197, 1, 501}`.

# `valid_at?`

```elixir
@spec valid_at?(t(), DateTime.t()) :: boolean()
```

Checks whether the certificate is valid at `datetime` (defaults to `DateTime.utc_now/0`).

# `verify_cert`

```elixir
@spec verify_cert(t(), t() | binary(), keyword()) :: :ok | {:error, term()}
```

Verifies an SM2-with-SM3 X.509 certificate's signature against an issuer certificate
(`%ExCEP.Crypto.Cert{}`) or raw 64/65-byte issuer public key.

## Options
- `:user_id` - SM2 user ID (default `"1234567812345678"`)
- `:check_validity` - verify `not_before <= now <= not_after` (default `true`)
- `:now` - reference `DateTime.t()` (default `DateTime.utc_now/0`)

---

*Consult [api-reference.md](api-reference.md) for complete listing*
