---
title: "Certificate Project"
description: "Derafu Certificate"
type: "docs"
category: "doc"
tags: [php]
authors: [Anonymous]
date: "2026-08-24"
last_update: "2026-08-24"
time_minutes: 1
draft: false
unlisted: false
url: "https://www.derafu.dev/docs/data/certificate"
---

# Derafu Certificate



---

## Introduction

Library for digital certificates

# Library for digital certificates

![GitHub last commit](https://img.shields.io/github/last-commit/derafu/certificate/main)
![CI Workflow](https://github.com/derafu/certificate/actions/workflows/ci.yml/badge.svg?branch=main&amp;event=push)
![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/derafu/certificate)
![GitHub Issues](https://img.shields.io/github/issues-raw/derafu/certificate)
![Total Downloads](https://poser.pugx.org/derafu/certificate/downloads)
![Monthly Downloads](https://poser.pugx.org/derafu/certificate/d/monthly)

A comprehensive PHP library for working with digital certificates, providing tools for loading, validating and generating certificates.

## Features

- **Certificate Loading**: Load certificates from files, data, arrays or keys.
- **Certificate Validation**: Validate certificates against specific requirements.
- **Certificate Generation**: Create self-signed certificates for testing.
- **Certificate Information**: Extract key information from certificates (ID, name, email, etc.).
- **Key Management**: Work with public and private keys, modulus, and exponent.

## Installation

```bash
composer require derafu/certificate
```

## Basic Usage

### Loading a Certificate

```php
use Derafu\Certificate\Service\CertificateLoader;

// Create a loader.
$loader = new CertificateLoader();

// Load from a file.
$certificate = $loader-&gt;loadFromFile(&#039;/path/to/certificate.p12&#039;, &#039;password&#039;);

// Load from data.
$certificate = $loader-&gt;loadFromData($certificateData, &#039;password&#039;);

// Load from array.
$certificate = $loader-&gt;loadFromArray([
    &#039;cert&#039; =&gt; $publicKey,
    &#039;pkey&#039; =&gt; $privateKey
]);

// Load from keys.
$certificate = $loader-&gt;loadFromKeys($publicKey, $privateKey);
```

### Accessing Certificate Information

```php
// Get basic certificate information.
$id = $certificate-&gt;getId(); // e.g., &quot;12345678-9&quot;
$name = $certificate-&gt;getName(); // e.g., &quot;John Doe&quot;
$email = $certificate-&gt;getEmail(); // e.g., &quot;john.doe@example.com&quot;

// Check certificate validity.
$isActive = $certificate-&gt;isActive(); // true if certificate is valid.
$expirationDays = $certificate-&gt;getExpirationDays(); // days until expiration.

// Get validity dates.
$validFrom = $certificate-&gt;getFrom(); // e.g., &quot;2025-01-01T00:00:00&quot;
$validTo = $certificate-&gt;getTo(); // e.g., &quot;2026-01-01T00:00:00&quot;

// Get certificate issuer.
$issuer = $certificate-&gt;getIssuer(); // e.g., &quot;Example CA&quot;

// Get key components.
$modulus = $certificate-&gt;getModulus();
$exponent = $certificate-&gt;getExponent();

// Get raw keys.
$publicKey = $certificate-&gt;getPublicKey(); // with headers.
$privateKey = $certificate-&gt;getPrivateKey(); // with headers.
$cleanPublicKey = $certificate-&gt;getPublicKey(true); // without headers.
$cleanPrivateKey = $certificate-&gt;getPrivateKey(true); // without headers.
```

### Validating a Certificate

```php
use Derafu\Certificate\Exception\CertificateException;
use Derafu\Certificate\Service\CertificateValidator;

$validator = new CertificateValidator();

try {
    $validator-&gt;validate($certificate);
    echo &quot;Certificate is valid&quot;;
} catch (CertificateException $e) {
    echo &quot;Certificate validation failed: &quot; . $e-&gt;getMessage();
}
```

### Creating a Fake Certificate for Testing

```php
use Derafu\Certificate\Service\CertificateLoader;
use Derafu\Certificate\Service\CertificateFaker;

$loader = new CertificateLoader();
$faker = new CertificateFaker($loader);

// Create a fake certificate with default values.
$certificate = $faker-&gt;createFake();

// Create a fake certificate with custom values.
$certificate = $faker-&gt;createFake(
    id: &#039;12345678-9&#039;,
    name: &#039;John Doe&#039;,
    email: &#039;john.doe@example.com&#039;,
    password: &#039;secure_password&#039;
);

// Export to PKCS#12 format.
$pkcs12Data = $certificate-&gt;getPkcs12(&#039;password&#039;);
file_put_contents(&#039;certificate.p12&#039;, $pkcs12Data);
```

### Using the Service

The `CertificateService` provides a unified interface to all library functionality:

```php
use Derafu\Certificate\Service\CertificateLoader;
use Derafu\Certificate\Service\CertificateFaker;
use Derafu\Certificate\Service\CertificateValidator;
use Derafu\Certificate\Service\CertificateService;

// Create the service with its dependencies.
$loader = new CertificateLoader();
$faker = new CertificateFaker($loader);
$validator = new CertificateValidator();
$service = new CertificateService($faker, $loader, $validator);

// Use the service for certificate operations.
$certificate = $service-&gt;loadFromFile(&#039;/path/to/certificate.p12&#039;, &#039;password&#039;);
$service-&gt;validate($certificate);

// Create a fake certificate for testing.
$fakeCertificate = $service-&gt;createFake(
    &#039;12345678-9&#039;,
    &#039;John Doe&#039;,
    &#039;john.doe@example.com&#039;
);
```

## Advanced Usage

### Creating a Self-Signed Certificate

For more control over certificate generation:

```php
use Derafu\Certificate\SelfSignedCertificate;
use Derafu\Certificate\Service\CertificateLoader;

// Create a self-signed certificate with custom values.
$selfSigned = new SelfSignedCertificate();
$selfSigned-&gt;setSubject(
    C: &#039;US&#039;,
    ST: &#039;California&#039;,
    L: &#039;San Francisco&#039;,
    O: &#039;Example Organization&#039;,
    OU: &#039;IT Department&#039;,
    CN: &#039;John Doe&#039;,
    emailAddress: &#039;john.doe@example.com&#039;,
    serialNumber: &#039;12345678-9&#039;
);

$selfSigned-&gt;setIssuer(
    CN: &#039;Example CA&#039;
);

$selfSigned-&gt;setValidity(365); // Valid for 1 year.
$selfSigned-&gt;setPassword(&#039;secure_password&#039;);

// Get the certificate array.
$certArray = $selfSigned-&gt;toArray();

// Load as a Certificate object.
$loader = new CertificateLoader();
$certificate = $loader-&gt;loadFromArray($certArray);
```

### Working with Asymmetric Keys

```php
use Derafu\Certificate\AsymmetricKeyHelper;

// Normalize a public key (add headers if missing).
$normalizedPublicKey = AsymmetricKeyHelper::normalizePublicKey($rawPublicKey);

// Normalize a private key (add headers if missing).
$normalizedPrivateKey = AsymmetricKeyHelper::normalizePrivateKey($rawPrivateKey);

// Generate a public key from modulus and exponent.
// Requirements: composer require phpseclib/phpseclib
$publicKey = AsymmetricKeyHelper::generatePublicKeyFromModulusExponent(
    $modulus,
    $exponent
);
```




---

## Certificate Class

Certificate Class

# Certificate Class

The `Certificate` class is the core component of the Derafu Certificate library, representing a digital certificate with its public and private keys and providing methods to access certificate details and properties.

## Overview

The `Certificate` class implements the `CertificateInterface` and provides functionality to:

- Access public and private keys.
- Extract certificate metadata (ID, name, email, issuer, etc.).
- Check certificate validity.
- Get certificate validity dates.
- Retrieve cryptographic components (modulus, exponent).
- Generate PKCS#12 data.

## Usage

### Creating a Certificate

To create a `Certificate` instance, you need a public key (certificate) and a private key:

```php
use Derafu\Certificate\Certificate;

$certificate = new Certificate($publicKey, $privateKey);
```

The constructor automatically normalizes the keys using `AsymmetricKeyHelper`.

### Getting Keys

```php
// Get both keys as an array.
$keys = $certificate-&gt;getKeys();
// Result: [&#039;cert&#039; =&gt; &#039;...public key...&#039;, &#039;pkey&#039; =&gt; &#039;...private key...&#039;]

// Get both keys without headers/footers.
$cleanKeys = $certificate-&gt;getKeys(clean: true);

// Get just the public key.
$publicKey = $certificate-&gt;getPublicKey();
// Alternatively.
$publicKey = $certificate-&gt;getCertificate();

// Get just the private key.
$privateKey = $certificate-&gt;getPrivateKey();

// Get clean keys (without headers/footers).
$cleanPublicKey = $certificate-&gt;getPublicKey(clean: true);
$cleanPrivateKey = $certificate-&gt;getPrivateKey(clean: true);
```

### Certificate Metadata

```php
// Get certificate ID (usually a document/tax number).
$id = $certificate-&gt;getId(); // e.g., &quot;12345678-9&quot;
$id = $certificate-&gt;getId(forceUpper:false); // with original case, e.g., &quot;12345678-k&quot;

// Get certificate owner&#039;s name.
$name = $certificate-&gt;getName();

// Get certificate owner&#039;s email.
$email = $certificate-&gt;getEmail();

// Get certificate issuer.
$issuer = $certificate-&gt;getIssuer();
```

### Certificate Validity

```php
// Check if certificate is valid (not expired).
$isActive = $certificate-&gt;isActive();

// Check if certificate is valid at a specific date.
$isActiveOn = $certificate-&gt;isActive(&#039;2025-06-01&#039;);

// Get certificate validity period.
$validFrom = $certificate-&gt;getFrom(); // e.g., &quot;2025-01-01T00:00:00&quot;
$validTo = $certificate-&gt;getTo(); // e.g., &quot;2026-01-01T00:00:00&quot;

// Get total validity period in days.
$totalDays = $certificate-&gt;getTotalDays();

// Get days remaining until expiration.
$daysRemaining = $certificate-&gt;getExpirationDays();

// Get days remaining from a specific date.
$daysRemainingFrom = $certificate-&gt;getExpirationDays(&#039;2025-06-01&#039;);
```

### Cryptographic Components

```php
// Get certificate raw data.
$data = $certificate-&gt;getData();

// Get private key details.
$privateKeyDetails = $certificate-&gt;getPrivateKeyDetails();

// Get modulus and exponent.
$modulus = $certificate-&gt;getModulus();
$exponent = $certificate-&gt;getExponent();

// With custom word wrapping.
$modulus = $certificate-&gt;getModulus(wordwrap: 75);
$exponent = $certificate-&gt;getExponent(wordwrap: 75);
```

### Exporting a Certificate

```php
// Export certificate as PKCS#12 data.
$pkcs12 = $certificate-&gt;getPkcs12(&#039;password&#039;);

// Save to a file.
file_put_contents(&#039;certificate.p12&#039;, $pkcs12);
```

## Error Handling

The `Certificate` class throws `CertificateException` when it encounters problems such as:

- Unable to extract the certificate ID.
- Unable to find the certificate name.
- Unable to find the certificate email.
- Unable to access the modulus or exponent.

Example:

```php
use Derafu\Certificate\Exception\CertificateException;

try {
    $id = $certificate-&gt;getId();
    $name = $certificate-&gt;getName();
    $email = $certificate-&gt;getEmail();
} catch (CertificateException $e) {
    echo &quot;Certificate error: &quot; . $e-&gt;getMessage();
}
```

## Implementation Details

### ID Extraction

The `getId()` method attempts to extract the certificate ID through multiple methods:

1. First, it checks the `serialNumber` field in the subject.
2. If not found, it looks for the ID in the Subject Alternative Name (SAN) extension.
3. If still not found, it throws a `CertificateException`.

### Certificate Validation

The `isActive()` method checks if the certificate is valid at the current date (or a specified date) by comparing it against the certificate&#039;s validity period.

### Cryptographic Components

The `getModulus()` and `getExponent()` methods extract these values from the private key details and return them as base64-encoded strings, which can be used for various cryptographic operations.




---

## Self-Signed Certificate

SelfSignedCertificate Class

# SelfSignedCertificate Class

The `SelfSignedCertificate` class provides functionality to generate self-signed certificates for testing and development purposes. It allows customization of certificate properties such as subject, issuer, validity period, and password protection.

## Overview

This class creates a digital certificate that includes:

1. A Certificate Authority (CA) certificate.
2. A user certificate signed by the CA.
3. Both packaged together in PKCS#12 format.

The generated certificate is suitable for testing electronic signature functionality without requiring a certificate from a commercial Certificate Authority.

## Basic Usage

```php
use Derafu\Certificate\SelfSignedCertificate;
use Derafu\Certificate\Service\CertificateLoader;

// Create with default settings.
$selfSigned = new SelfSignedCertificate();
$certificateArray = $selfSigned-&gt;toArray();

// Load as a Certificate object.
$loader = new CertificateLoader();
$certificate = $loader-&gt;loadFromArray($certificateArray);
```

## Configuration Methods

### Setting the Subject

The subject represents the owner of the certificate:

```php
$selfSigned-&gt;setSubject(
    C: &#039;US&#039;,                              // Country code (2 letters).
    ST: &#039;California&#039;,                     // State/Province.
    L: &#039;San Francisco&#039;,                   // Locality/City.
    O: &#039;Example Corporation&#039;,             // Organization.
    OU: &#039;IT Department&#039;,                  // Organizational Unit.
    CN: &#039;John Doe&#039;,                       // Common Name (full name).
    emailAddress: &#039;john.doe@example.com&#039;, // Email address.
    serialNumber: &#039;12345678-9&#039;,           // ID/Serial number (tax ID, etc.).
    title: &#039;System Administrator&#039;         // Title.
);
```

Only `CN`, `emailAddress`, and `serialNumber` are strictly required. The method will throw a `CertificateException` if any of these are empty.

### Setting the Issuer

The issuer represents the Certificate Authority that issues the certificate:

```php
$selfSigned-&gt;setIssuer(
    C: &#039;US&#039;,                           // Country code
    ST: &#039;Washington&#039;,                  // State/Province
    L: &#039;Seattle&#039;,                      // Locality/City
    O: &#039;Example CA&#039;,                   // Organization
    OU: &#039;Certificate Authority&#039;,       // Organizational Unit
    CN: &#039;Example Root CA&#039;,             // CA Name
    emailAddress: &#039;ca@example.com&#039;,    // CA Email
    serialNumber: &#039;87654321-0&#039;         // CA ID
);
```

### Setting the Validity Period

```php
// Set validity to 730 days (2 years).
$selfSigned-&gt;setValidity(730);
```

The default validity period is 365 days (1 year).

### Setting the Password

```php
// Set password for the private key.
$selfSigned-&gt;setPassword(&#039;secure_password&#039;);
```

The default password is `&#039;i_love_derafu&#039;`.

## Generating the Certificate

### Getting the Certificate Array

```php
// Get the certificate as an array with &#039;cert&#039; and &#039;pkey&#039; elements.
$certificateArray = $selfSigned-&gt;toArray();

// The array contains:
// [
//     &#039;cert&#039; =&gt; &#039;...public key certificate...&#039;,
//     &#039;pkey&#039; =&gt; &#039;...private key...&#039;
// ]
```

### Getting the Raw PKCS#12 Data

```php
// Get the toPkcs12() method result (PKCS#12 binary data).
$pkcs12Data = $selfSigned-&gt;toPkcs12();

// Save to a file.
file_put_contents(&#039;certificate.p12&#039;, $pkcs12Data);
```

## Certificate Structure

The generated certificate consists of:

1. An issuer (CA) certificate that is self-signed.
2. A subject certificate that is signed by the issuer.
3. Both certificates&#039; private keys.

The PKCS#12 container includes both certificates and is password-protected using the specified password.

## Default Values

If you create a `SelfSignedCertificate` without any customization, it will use the following default values:

### Default Subject

- Country: `CL` (Chile).
- State: `Colchagua`.
- Locality: `Santa Cruz`.
- Organization: `Intergalactic Robots Organization`.
- Organizational Unit: `Technology`.
- Common Name: `Daniel Bot`.
- Email: `daniel.bot@example.com`.
- Serial Number: `11222333-9`.
- Title: `Bot`.

### Default Issuer

- Country: `CL` (Chile).
- State: `Colchagua`.
- Locality: `Santa Cruz`.
- Organization: `Derafu`.
- Organizational Unit: `Technology`.
- Common Name: `Derafu Test Certificate Authority`.
- Email: `fakes-certificates@derafu.org`.
- Serial Number: `76192083-9`.

### Other Defaults

- Validity: 365 days.
- Password: `i_love_derafu`.

## Implementation Details

The `SelfSignedCertificate` class uses the PHP OpenSSL extension to:

1. Generate a key pair for the issuer.
2. Create a Certificate Signing Request (CSR) for the issuer.
3. Self-sign the issuer&#039;s CSR to create the issuer certificate.
4. Generate a key pair for the subject.
5. Create a CSR for the subject.
6. Sign the subject&#039;s CSR with the issuer&#039;s certificate.
7. Package everything into a PKCS#12 container.

The process mimics a real CA-issued certificate but is entirely self-contained and suitable for testing purposes.




---

## Asymmetric Key Helper

AsymmetricKeyHelper Class

# AsymmetricKeyHelper Class

The `AsymmetricKeyHelper` class provides utilities for working with RSA certificates and keys. It offers methods to normalize public and private keys and to generate public keys from modulus and exponent values.

## Overview

When working with digital certificates and electronic signatures, you often need to handle RSA key components in different formats. The `AsymmetricKeyHelper` class solves common problems related to key formatting and generation:

1. Adding standard PEM headers and footers to raw key data.
2. Converting between key components (modulus, exponent) and full key format.

## Key Normalization

### Normalizing a Public Key

```php
use Derafu\Certificate\AsymmetricKeyHelper;

// Raw public key without headers.
$rawPublicKey = &quot;MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvTLIKu... (more base64 data)&quot;;

// Normalize the public key (add headers and footers).
$normalizedPublicKey = AsymmetricKeyHelper::normalizePublicKey($rawPublicKey);

// Result:
// -----BEGIN CERTIFICATE-----
// MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvTLIKu...
// (more base64 data, wrapped, by default, at 64 characters per line)
// -----END CERTIFICATE-----
```

### Normalizing a Private Key

```php
// Raw private key without headers.
$rawPrivateKey = &quot;MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkA... (more base64 data)&quot;;

// Normalize the private key (add headers and footers).
$normalizedPrivateKey = AsymmetricKeyHelper::normalizePrivateKey($rawPrivateKey);

// Result:
// -----BEGIN PRIVATE KEY-----
// MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkA...
// (more base64 data, wrapped, by default, at 64 characters per line)
// -----END PRIVATE KEY-----
```

### Custom Line Length

Both normalization methods support a custom line length for wrapping the key data:

```php
// Wrap lines at 75 characters instead of the default 64.
$normalizedPublicKey = AsymmetricKeyHelper::normalizePublicKey($rawPublicKey, 75);
$normalizedPrivateKey = AsymmetricKeyHelper::normalizePrivateKey($rawPrivateKey, 75);
```

## Key Generation

### Generating a Public Key from Modulus and Exponent

You can generate a complete public key if you have the modulus and exponent components:

```php
// Base64-encoded modulus and exponent.
$modulus = &quot;wKhpaf5AYomI+0/tLxJtvjHVCveRYYZ9j0yDlL...&quot;;
$exponent = &quot;AQAB&quot;;

// Generate public key.
$publicKey = AsymmetricKeyHelper::generatePublicKeyFromModulusExponent(
    $modulus,
    $exponent
);

// Result is a complete public key in PKCS1 format:
// -----BEGIN RSA PUBLIC KEY-----
// MIIBCgKCAQEAwKhpaf5AYomI+0/tLxJtvjHVCveRYYZ9j0yDlL...
// -----END RSA PUBLIC KEY-----
```

This method requires the `phpseclib3/phpseclib` library. If the library is not installed, it will throw a `LogicException` with instructions to install it.

## Common Use Cases

### Preparing Keys for Use with OpenSSL Functions

Many OpenSSL functions require properly formatted keys with headers and footers:

```php
// Normalize keys before using with OpenSSL.
$normalizedPublicKey = AsymmetricKeyHelper::normalizePublicKey($rawPublicKey);
$normalizedPrivateKey = AsymmetricKeyHelper::normalizePrivateKey($rawPrivateKey);

// Now use with OpenSSL functions.
$signature = openssl_sign($data, $signature, $normalizedPrivateKey, OPENSSL_ALGO_SHA256);
$result = openssl_verify($data, $signature, $normalizedPublicKey, OPENSSL_ALGO_SHA256);
```

### Reconstructing Public Keys

In some systems, especially with hardware security modules (HSMs) or smart cards, you might only have access to the modulus and exponent components:

```php
// Reconstruct the public key from components.
$publicKey = AsymmetricKeyHelper::generatePublicKeyFromModulusExponent(
    $modulus,
    $exponent
);

// Use for verification.
$result = openssl_verify($data, $signature, $publicKey, OPENSSL_ALGO_SHA256);
```

## Implementation Details

### Public Key Normalization

The `normalizePublicKey()` method:

1. Checks if the key already contains the &quot;BEGIN CERTIFICATE&quot; header.
2. If not, adds the appropriate BEGIN/END headers.
3. Wraps the content to the specified line length.
4. Returns the normalized key.

### Private Key Normalization

The `normalizePrivateKey()` method:

1. Checks if the key already contains the &quot;BEGIN PRIVATE KEY&quot; header.
2. If not, adds the appropriate BEGIN/END headers.
3. Wraps the content to the specified line length.
4. Returns the normalized key.

### Public Key Generation

The `generatePublicKeyFromModulusExponent()` method:

1. Decodes the base64-encoded modulus and exponent.
2. Creates BigInteger instances from the binary data.
3. Loads these values into a RSA key object using phpseclib.
4. Exports the key in PKCS1 format.
5. Returns the complete public key string.




---

## Certificate Service

CertificateService Class

# CertificateService Class

The `CertificateService` is the main entry point for working with digital certificates in the Derafu Certificate library. It provides a unified interface to all the key functionality like loading, validating, and creating certificates.

## Overview

The `CertificateService` follows the service pattern, acting as a facade for:

- `CertificateFaker`: For creating test certificates.
- `CertificateLoader`: For loading certificates from various sources.
- `CertificateValidator`: For validating certificates.

By using the service, you can access all the library&#039;s functionality through a single interface.

## Basic Usage

### Setting Up the Service

```php
use Derafu\Certificate\Service\CertificateLoader;
use Derafu\Certificate\Service\CertificateFaker;
use Derafu\Certificate\Service\CertificateValidator;
use Derafu\Certificate\Service\CertificateService;

// Create dependencies.
$loader = new CertificateLoader();
$faker = new CertificateFaker($loader);
$validator = new CertificateValidator();

// Create the service.
$service = new CertificateService($faker, $loader, $validator);
```

### Loading Certificates

The service provides methods to load certificates from various sources:

```php
// Load from a PKCS#12 file.
$certificate = $service-&gt;loadFromFile(&#039;/path/to/certificate.p12&#039;, &#039;password&#039;);

// Load from PKCS#12 data.
$certificate = $service-&gt;loadFromData($pkcs12Data, &#039;password&#039;);

// Load from a certificate array.
$certificate = $service-&gt;loadFromArray([
    &#039;cert&#039; =&gt; $publicKey,
    &#039;pkey&#039; =&gt; $privateKey
]);

// Load directly from key strings.
$certificate = $service-&gt;loadFromKeys($publicKey, $privateKey);
```

### Validating Certificates

```php
use Derafu\Certificate\Exception\CertificateException;

try {
    $service-&gt;validate($certificate);
    echo &quot;Certificate is valid!&quot;;
} catch (CertificateException $e) {
    echo &quot;Validation failed: &quot; . $e-&gt;getMessage();
}
```

### Creating Test Certificates

```php
// Create with default values.
$certificate = $service-&gt;createFake();

// Create with custom values.
$certificate = $service-&gt;createFake(
    id: &#039;12345678-9&#039;,
    name: &#039;John Doe&#039;,
    email: &#039;john.doe@example.com&#039;
);

// Use the certificate.
$id = $certificate-&gt;getId();
$name = $certificate-&gt;getName();
$isValid = $certificate-&gt;isActive();
```

## Complete Example

```php
// Initialize the service.
$loader = new CertificateLoader();
$faker = new CertificateFaker($loader);
$validator = new CertificateValidator();
$service = new CertificateService($faker, $loader, $validator);

// Create a test certificate.
$certificate = $service-&gt;createFake(
    id: &#039;12345678-9&#039;,
    name: &#039;John Doe&#039;,
    email: &#039;john.doe@example.com&#039;
);

// Extract certificate data.
echo &quot;Certificate ID: &quot; . $certificate-&gt;getId() . &quot;\n&quot;;
echo &quot;Certificate Name: &quot; . $certificate-&gt;getName() . &quot;\n&quot;;
echo &quot;Valid until: &quot; . $certificate-&gt;getTo() . &quot;\n&quot;;
echo &quot;Days remaining: &quot; . $certificate-&gt;getExpirationDays() . &quot;\n&quot;;

// Validate the certificate.
try {
    $service-&gt;validate($certificate);
    echo &quot;Certificate is valid\n&quot;;
} catch (CertificateException $e) {
    echo &quot;Invalid certificate: &quot; . $e-&gt;getMessage() . &quot;\n&quot;;
}

// Export the certificate.
$pkcs12Data = $certificate-&gt;getPkcs12(&#039;password&#039;);
file_put_contents(&#039;certificate.p12&#039;, $pkcs12Data);

// Later, load the certificate back.
$loadedCertificate = $service-&gt;loadFromFile(&#039;certificate.p12&#039;, &#039;password&#039;);
```

## Customizing the Service

### Custom Validator

You can create a custom validator by implementing the `CertificateValidatorInterface`:

```php
use Derafu\Certificate\Contract\CertificateInterface;
use Derafu\Certificate\Contract\CertificateValidatorInterface;
use Derafu\Certificate\Exception\CertificateException;

class MyCustomValidator implements CertificateValidatorInterface
{
    public function validate(CertificateInterface $certificate): void
    {
        // Implement your validation logic.
        if (!$certificate-&gt;isActive()) {
            throw new CertificateException(
                &#039;Certificate is expired.&#039;
            );
        }

        // Add specific validation for your use case.
        if ($certificate-&gt;getExpirationDays() &lt; 30) {
            throw new CertificateException(
                &#039;Certificate will expire in less than 30 days.&#039;
            );
        }
    }
}

// Use your custom validator.
$customValidator = new MyCustomValidator();
$service = new CertificateService($faker, $loader, $customValidator);
```

## Service Components

### CertificateLoader

The `CertificateLoader` component handles loading certificates from various sources:

- PKCS#12 files.
- PKCS#12 binary data.
- Array of keys.
- Individual public and private keys.

### CertificateFaker

The `CertificateFaker` component provides a way to create self-signed certificates for testing purposes:

- Create certificates with custom subject information.
- Create certificates with custom issuer information.
- Create certificates with custom validity periods.

Under the hood, it uses the `SelfSignedCertificate` class.

### CertificateValidator

The `CertificateValidator` component validates certificates according to specific requirements:

- Checks if the certificate ID (RUN) is properly formatted.
- Ensures that &quot;K&quot; in the ID is uppercase.
- Verifies that the certificate is not expired.

The default validator is designed for Chilean certificates used with the SII (Servicio de Impuestos Internos), but you can implement your own validator for different requirements.





---
Last updated on 24/08/2026
#php
