phpday 2027 - Call for Papers

openssl_x509_parse

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_x509_parse — X509 証明書をパースし、配列として情報を返す

説明

function openssl_x509_parse(OpenSSLCertificate|string $certificate, bool $short_names = true): array|false

openssl_x509_parse() は、指定した certificate に関する情報を返します。この情報には 題名、発行者名、目的、発効日および有効期限等が含まれます。

パラメータ

certificate

X509証明書。正しい値の一覧は キー/証明書パラメータ を参照ください。

short_names

short_names は、配列中でのデータの添字付けの 方法を設定します。short_names が true の場合 (デフォルト)、フィールドは短縮型で添字が付けられます。そうでない場合、 長い名前が使用されます。例えば、CN は commonName の短縮型です。

戻り値

成功した場合に証明書のフィールドを含む配列を、失敗した場合に false を返します。

alias は、証明書にエイリアスがある場合だけ存在します。 以下に示すそれ以外のキーは、常に存在します。

openssl_x509_parse() が返す配列
キー 型 説明
name string subject の識別名を 1 つの文字列で表したもの。各要素はスラッシュで区切られます。 例えば /C=US/O=Example/CN=example.com のようになります。
subject array subject の識別名。キーは、short_names が true の場合は CN のような短縮名、 そうでない場合は commonName のような長い名前です。 各値は UTF-8 文字列です。同じ要素が複数回現れる場合は、 UTF-8 文字列の配列になります。
hash string subject の識別名のハッシュ値を小文字の 16 進数で表したもの。 OpenSSL が CA ディレクトリから証明書を探すときに使う 8 桁の値です。 証明書のフィンガープリントではありません。フィンガープリントについては openssl_x509_fingerprint() を参照ください。
issuer array 発行者の識別名。形式は subject と同じです。
version int 証明書に格納されている、バージョンフィールドの生の値。 証明書のバージョンとして通常表示される番号より 1 小さい値です。 バージョン 1 の証明書は 0、バージョン 2 の証明書は 1、バージョン 3 の証明書は 2 になります。
serialNumber string シリアル番号を 10 進数で表したもの。シリアル番号が大きい場合は、 先頭に 0x を付けた 16 進数の文字列になります。
serialNumberHex string シリアル番号を大文字の 16 進数で表したもの。
validFrom string 有効期間の開始日時を ASN.1 の形式で表したもの。UTCTime (YYMMDDHHMMSSZ) と GeneralizedTime (YYYYMMDDHHMMSSZ) のいずれかです。
validTo string 有効期間の終了日時。形式は validFrom と同じです。
validFrom_time_t int 有効期間の開始日時を表す Unix タイムスタンプ。日時をパースできなかった場合は -1 になります。
validTo_time_t int 有効期間の終了日時を表す Unix タイムスタンプ。日時をパースできなかった場合は -1 になります。
alias string 証明書のエイリアス (フレンドリ名)。設定されている場合だけ存在します。
signatureTypeSN string 署名アルゴリズムの短縮名。
signatureTypeLN string 署名アルゴリズムの長い名前。
signatureTypeNID int 署名アルゴリズムを表す数値の識別子 (OpenSSL の NID)。
purposes array 目的ごとの確認結果。キーは目的の ID で、 X509_PURPOSE_* 定数の値です。各値は、後述する配列です。
extensions array 証明書の拡張。キーは subjectAltName のような拡張の短縮名で、 短縮名がない拡張は OID がキーになります。 各値は拡張の内容を表すテキストで、テキストとして出力できない場合は 拡張の生データになります。どのキーが存在するかは証明書によって異なります。 この配列は short_names の影響を受けません。

purposes の各要素には、以下のキーがあります。

目的ごとの配列
キー 型 説明
0 bool エンドエンティティ証明書として、この目的に使える場合に true になります。
1 bool CA 証明書として、この目的に使える場合に true になります。
2 string 目的の名前。short_names が true の場合は sslclient のような短縮名、 そうでない場合は SSL client のような長い名前です。

変更履歴

バージョン 説明
8.4.0 すべての OpenSSL バージョンで、UTCTime に秒が含まれていない証明書をパースできなくなりました。 OpenSSL のバージョン 3.3 以降を使っていた場合は、以前からパースできませんでした。
8.0.0 certificate は、 OpenSSLCertificate クラスのインスタンスを受け入れるようになりました。 これより前のバージョンでは、 OpenSSL X.509 型のリソースを受け入れていました。
+add a note

User Contributed Notes 7 notes

up
10
nathanael at dihedral dot de
20 years ago
When dealing with the purposes of a x509 crt file
the output of openssl_x509_parse gives an array with following for the purposes:
each new array ([purposes][1], [purposes][2] for example) is a new purpose check
I compared this output with the output of the command
# openssl x509 -purpose -in <x509crt_file>
the result i got was that
[purposes][x][2] quite obviously is the name of the purpose checked 
[purposes][x][1] corresponds to the tested purpose (as named in [purposes][x][2]) acting as CA
[purposes][x][0] corresponds to the general availability of the purpose

[purposes] => Array
    (
        [1] => Array
            (
                [0] => 1
                [1] => 1
                [2] => sslclient
            )

        [2] => Array
            (
                [0] => 1
                [1] => 1
                [2] => sslserver
            )

        [3] => Array
            (
                [0] => 1
                [1] => 1
                [2] => nssslserver
            )

        [4] => Array
            (
                [0] => 1
                [1] => 1
                [2] => smimesign
            )

        [5] => Array
            (
                [0] => 1
                [1] => 1
                [2] => smimeencrypt
            )

        [6] => Array
            (
                [0] => 1
                [1] => 1
                [2] => crlsign
            )

        [7] => Array
            (
                [0] => 1
                [1] => 1
                [2] => any
            )

        [8] => Array
            (
                [0] => 1
                [1] => 1
                [2] => ocsphelper
            )

    )
up
4
maarten at xolphin dot nl
21 years ago
At this time very useful X509 oids (like streetAddress, postalCode and others) are missing. You can find a list of them at http://www.alvestrand.no/objectid/2.5.4.html, I hope they get included to openssl-x509-parse soon.

Until then you can get these oids anyway like this:

<?
  function getOID($OID, $ssl)
  {
    preg_match('/\/' . $OID  . '=([^\/]+)/', $ssl, $matches);
    return $matches[1];
  }

  $cert = file_get_contents('test.crt');
  $ssl = openssl_x509_parse($cert);
  $Address = getOID('2.5.4.9', $ssl['name']);
  $ZipCode = getOID('2.5.4.17', $ssl['name']);
  $Postbox = getOID('2.5.4.18', $ssl['name']);
?>

The parseCert function from the Horde framework can be usefull for this too.
up
1
Stilez
10 years ago
The valid from/to info is returned twice, in two different formats. They can be converted to normal datetime objects like this:

$x509_data = openssl_x509_parse($cert);
date_create_from_format('ymdHise', $x509_data['validFrom'])->format('c');
date_create( '@' .  $x509_data['validFrom_time_t'])->format('c');
/* these give the same result */

To get a human-readable format directly (or any other formatted string) instead of a datetime object, use this:

date_create_from_format('ymdHise', $x509_data['validFrom'])->format('c');
or
date_create( '@' .  $x509_data['validFrom_time_t'])->format('c');

The same applies to validTo and validTo_time_t
up
2
smgallo at buffalo dot edu
22 years ago
The identifier for the email portion of certificates in the name and subject array have changed since PHP4.  In PHP 4.3.0 the following array was returned (displayed my print_r())

[name] => /O=Grid/O=Globus/O=CCR Grid Portal/OU=Portal User/CN=Test User/Email=test@nospam.buffalo.edu
[subject] => Array
(
   [O] => Grid/O=Globus/O=CCR Grid Portal
   [OU] => Portal User
   [CN] => Test User
   [Email] => test@nospam.buffalo.edu
...

The result in PHP5 is (note Email -> emailAddress):

[name] => /O=Grid/O=Globus/O=CCR Grid Portal/OU=Portal User/CN=Test User/emailAddress=test@nospam.buffalo.edu
[subject] => Array
(
   [O] => Grid/O=Globus/O=CCR Grid Portal
   [OU] => Portal User
   [CN] => Test User
   [emailAddress] => test@nospam.buffalo.edu
...

Of course, the manual DOES say this could happen.  :)
up
2
koukopoulos at gmail dot com
18 years ago
Re: the previous note: support for the x509v3 extensions was added in PHP 5.2. Also in PHP5 prior to 5.2.4 the values of the x509v3 extensions were not decoded and were returned in the DER binary representation. Therefore in order to read the contents of the v3 extensions you have to parse the relevant ASN.1 structures yourself.

For example if one needs to read an IA5STRING value in a private extension with the OID 1.3.6.1.4.1.7782.3.3 one can do :

<?php

/* parse a DER encoded representation 
   of a IA5STRING of length < 127 */
function asn1der_ia5string($str)
{
    $len=strlen($str)-2;
    if ($len < 0 && $len > 127) {
        return false;
    }

    /* check tag and len */
    if (22 != (ord($str[$pos++]) & 0x1f) && 
    ord($str[$pos++]) != $len) {
    /* not a valid DER encoding of an IA5STRING */
    return false;
    }

    return substr($str, 2,  $len);
}
$cert = openssl_x509_parse($pemcert);
print (asn1der_ia5string($cert['extensions']['1.3.6.1.4.1.7782.3.3'])); // prints decoded ascii string

?>

In newer versions (>5.2.3) the extensions are returned in a 'readable format'. For example:

<?php print_r(openssl_x509_parse(...)); ?>
will result in
<?
Array
(
    [name] => /C=GR/O=SOMETHING/CN=ME/
    ...
    [extensions] => Array
        (
            [basicConstraints] => CA:FALSE
            [keyUsage] => Digital Signature, Non Repudiation, Key Encipherment
            [extendedKeyUsage] => E-mail Protection, TLS Web Client Authentication
            [nsCertType] => SSL Client, S/MIME
            ....
?>
up
0
s dot stok at rollerscapes dot net
16 years ago
Alternative subjects can read as extensions.

[extensions]
            [subjectAltName] => DNS:*.cacert.org, DNS:cacert.org, DNS:*.cacert.net, DNS:cacert.net, DNS:*.cacert.com, DNS:cacert.com
up
-4
zioproto at gmail dot com
18 years ago
To read an extension from a X.509 certificate, you can proceed like this if you know the OID

//Read the certificate from file
$cert = file_get_contents('test.crt');
$ssl = openssl_x509_parse($cert);

$ext_value =  $ssl['extensions']['1.2.3.4.5.6'];
echo $ext_value

--------------------------------

Because the $ssl array is not documented, you can easily see its contents like this:

  //To print out all the array!
  print_r(array_values($ssl)); 
  print_r(array_keys($ssl));
To Top