How to use openssl_x509_parse and openssl_x509_verify on php?

Member

by aubrey , in category: PHP General , 6 months ago

How to use openssl_x509_parse and openssl_x509_verify on php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hal.littel , 6 months ago

@aubrey 

To use the openssl_x509_parse and openssl_x509_verify functions in PHP, you need to have the OpenSSL extension installed and enabled in your PHP configuration. Here is an example of how to use these functions:

  1. Loading a certificate from a file: $certificate = file_get_contents('/path/to/certificate.pem');
  2. Parsing the certificate: $parsedCertificate = openssl_x509_parse($certificate); var_dump($parsedCertificate); This function will return an associative array containing the parsed certificate information. You can access individual fields using array keys like $parsedCertificate['subject'], $parsedCertificate['issuer'], etc.
  3. Verifying a certificate against a trusted CA store: $trustedCACertificate = file_get_contents('/path/to/ca_certificate.pem'); $result = openssl_x509_verify($certificate, $trustedCACertificate); if ($result === 1) { // Certificate is valid } elseif ($result === 0) { // Certificate is not valid } else { // An error occurred during verification } In this example, the function openssl_x509_verify is used to verify if the given certificate is trusted by the CA indicated by ca_certificate.pem. A return value of 1 indicates a successful verification, 0 indicates the certificate is not valid, and any other value indicates an error occurred during verification.


Remember, these functions require the OpenSSL extension to be enabled in your PHP installation. You can check if it is enabled by running phpinfo() or using the php -i command in your terminal.