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.), including the fields that are repeated.
  • Check certificate validity.
  • Get certificate validity dates.
  • Retrieve cryptographic components (modulus, exponent).
  • Generate PKCS#12 data.

Usage

Creating a Certificate

The usual way to get a Certificate is the loader. It can also be created directly, with the certificate and, optionally, its private key and its trust chain:

use Derafu\Certificate\Certificate;

$certificate = new Certificate($certificatePem, $privateKeyPem);

// Without private key, or with the trust chain.
$certificate = new Certificate($certificatePem);
$certificate = new Certificate($certificatePem, $privateKeyPem, [$intermediateCaPem]);

The constructor automatically normalizes the certificate, the key and the chain using AsymmetricKeyHelper: the PEM headers and footers are added if they are missing.

The last argument is the OpenSSL service that the certificate uses. It is optional: without it, it uses OpenSsl.

Getting Keys

// Get both keys as an array.
$keys = $certificate->getKeys();
// Result: ['cert' => '...certificate...', 'pkey' => '...private key...', 'chain' => [...]]
// `pkey` is `null` if the certificate was loaded without a private key.

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

// Get the certificate (the X.509 certificate of the holder, in PEM).
$certificatePem = $certificate->getCertificate();

// Get the public key. It is not the certificate: it is the public key that the
// certificate has inside.
$publicKey = $certificate->getPublicKey();

// Get the private key. It throws a CertificateException if the certificate was
// loaded without it.
$privateKey = $certificate->getPrivateKey();

// Get them clean (without headers/footers).
$cleanCertificate = $certificate->getCertificate(clean: true);
$cleanPublicKey = $certificate->getPublicKey(clean: true);
$cleanPrivateKey = $certificate->getPrivateKey(clean: true);

Certificate Metadata

// Get the certificate ID.
$id = $certificate->getId(); // e.g., "12345678-9"
$id = $certificate->getId(forceUpper: false); // with original case, e.g., "12345678-k"

// Get certificate owner's name (CN of the subject).
$name = $certificate->getName();

// Get certificate owner's email.
$email = $certificate->getEmail();

// Get certificate issuer (CN of the issuer).
$issuer = $certificate->getIssuer();

Repeated Fields

A distinguished name is a list of attributes, and the standard (RFC 5280) does not forbid that an attribute appears more than once. So a certificate can have two CN, two email addresses or two serialNumber. OpenSSL gives a text when the field appears once and a list when it is repeated.

Because of that, every field has two methods:

Singular Plural Field
getId() getIds() serialNumber of the subject (or the ID of the extension)
getName() getNames() CN of the subject
getEmail() getEmails() emailAddress of the subject
getIssuer() getIssuers() CN of the issuer
$certificate->getNames();  // ["Ana Perez", "Ana P."]
$certificate->getName();   // "Ana Perez" (the first one)

$certificate->getEmails(); // ["[email protected]"] (a list, even if there is only one)
  • The plural methods always return a list of texts, in the order of the certificate. The list is empty if the field is not in the certificate.
  • The singular methods return the first value, and throw a CertificateException if there is none. Use the plural method when the field can be repeated.

Certificate Validity

// Check if certificate is valid (not expired).
$isActive = $certificate->isActive();

// Check if certificate is valid at a specific date.
$isActiveOn = $certificate->isActive('2025-06-01');

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

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

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

// Get days remaining from a specific date.
$daysRemainingFrom = $certificate->getExpirationDays('2025-06-01');

Cryptographic Components

// Get certificate raw data.
$data = $certificate->getData();

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

// Get public key details.
$publicKeyDetails = $certificate->getPublicKeyDetails();

// Get modulus and exponent (of the public key, they exist only for RSA keys).
$modulus = $certificate->getModulus();
$exponent = $certificate->getExponent();

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

Trust Chain and Bundle

// The intermediate CA certificates (empty if there are none).
$chain = $certificate->getCertificateChain();
$cleanChain = $certificate->getCertificateChain(clean: true);

// The certificate followed by its chain, as one PEM bundle.
$bundle = $certificate->getCertificateBundle();

Exporting a Certificate

// Export the certificate, its private key and its trust chain (if it has one) as a
// PKCS#12, protected with the password.
$pkcs12 = $certificate->getPkcs12('password');

// Save to a file.
file_put_contents('certificate.p12', $pkcs12);

A certificate without a private key can not be exported: getPkcs12() throws a CertificateException.

Error Handling

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

  • Unable to extract the certificate ID, name, email or issuer (the field is not in the certificate).
  • Unable to read the data, the public key or the private key (for example, the content is not a certificate).
  • The private key is not available (the certificate was loaded without it): getPrivateKey(), getPrivateKeyDetails() and getPkcs12().
  • Unable to access the modulus or exponent (the key is not RSA).

When the failure is of OpenSSL, the exception has its errors in getErrors(), as translatable messages. See Exceptions.

Example:

use Derafu\Certificate\Exception\CertificateException;

try {
    $id = $certificate->getId();
    $name = $certificate->getName();
    $email = $certificate->getEmail();
} catch (CertificateException $e) {
    echo "Certificate error: " . $e->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 (otherName).
  3. If still not found, getIds() returns an empty list and getId() 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’s validity period.

Cryptographic Components

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

On this page

Last updated on 30/10/2026 by Anonymous