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();

Serial Number, Fingerprint and Issuer Name

What identifies a certificate, besides its holder: the serial number that its issuer assigned, the fingerprint of its DER, and the distinguished name of its issuer. The issuer name and the serial number are the identification that XML Signature (X509IssuerSerial) and XAdES (IssuerSerial) use for it.

// The serial number, in decimal whatever its size (a serial number can have 160 bits).
$serial = $certificate->getSerialNumber(); // e.g., "17517295961972146475"

// The fingerprint: the hash of the DER of the certificate, in hexadecimal.
$fingerprint = $certificate->getFingerprint();           // sha256 by default.
$sha1 = $certificate->getFingerprint('sha1');
$raw = $certificate->getFingerprint('sha256', binary: true); // the bytes of the hash.

// The distinguished name of the issuer, as RFC 4514 writes it.
$issuerDn = $certificate->getIssuerDn();
// e.g., "CN=UBL TC,OU=UBL Technical Committee,O=OASIS,L=Burlington,ST=Massachusetts,C=US"

getIssuerDn() writes the attributes in the inverse order to the one of the certificate, as RFC 4514 says, separated by commas. The attributes of a same set are joined with +, the special characters are escaped (,, +, ", \, <, >, ;, a space or # at the start and a space at the end), and the attributes that RFC 4514 gives a name to (CN, L, ST, O, OU, C, STREET, DC, UID) are written with it. The other ones (emailAddress and serialNumber, for example) are written with their OID and their value in hexadecimal: 1.2.840.113549.1.9.1=#16.... It is read from the DER of the certificate, so the order and the repeated attributes are the ones of the certificate. getIssuer() is only the common name of the issuer.

The fingerprint of an algorithm that is not one of hash_algos() is a CertificateException.

Issuer and Serial Number as DER

// The DER of the IssuerSerial (RFC 5035): the issuer, as a GeneralNames with a
// directoryName, and the serial number, as the certificate has them. It is what
// the IssuerSerialV2 of XAdES has, in base64.
$der = $certificate->getIssuerSerialDer();
$issuerSerialV2 = base64_encode($der);

Comparing Distinguished Names

The same name can be written in many ways: with the names of the attributes or with their OIDs, in the order of the certificate or in the inverse one, with other case, with escapes. Derafu\Certificate\DistinguishedName::equals() tells if two texts are the same name, as the attributes that they have:

use Derafu\Certificate\DistinguishedName;

DistinguishedName::equals(
    'CN=Authority,O=Company,C=CL',
    'C=CL, o=company, 2.5.4.3=authority'
); // true

It ignores the case and the spaces around the values, accepts the attributes by name (CN, emailAddress, E, S…) or by OID (2.5.4.3, OID.2.5.4.3), the escapes with a backslash (\,, \2C) and the values in hexadecimal (#0c01..), commas and semicolons between the attributes, any order for the attributes of a set (+), and the order of the certificate or the inverse one. A text that is not a name (without =, with a backslash at the end, a hexadecimal value that is not valid) is not the same as anything.

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 09/11/2026 by Anonymous