PHP SSL Certificate Serial Number in hexadecimal
I need to display SSL certificat information about Serial Number. When I use
$cert = file_get_contents('mycert.crt');
$data=openssl_x509_parse($cert,true);
$data['serialNumber']
I receive like -5573199485241205751 But when I run command openssl x509 -in 'mycert.crt' -noout -serial I receive serial=B2A80498A3C开发者_StackOverflow中文版EDC09 is it possible receive in PHP? Thanks.
You are probably recieving the serial number as a byte array. Convert those bytes to hex and you should get the serial that you are seeing using openssl.
Thanks Petey B the idea was interesting so have help me to find direction to search. The solution is:
$serial_number= strtoupper(dechex($serial_number));
php > $value = hexdec('B2A80498A3CEDC09');
php > echo dechex($value);
b2a80498a3cee000
That doesn't seem to work. Probably due to float conversion.
I saw one solution with bcmath.
Here's from confusa (http://www.assembla.com/code/confusa/git/nodes/lib/ca/Certificate.php?rev=a80a040c97fde2c170bb290d756c6729883fe80a):
/*
* PHP will return the serial as an integer, whereas
* everybody else use the hex-represenatation of the
* number.
*
* Due to the fact that Comodo uses *insanely* large
* serial-numbers, we need to be a bit creative when we
* get the serial as PHP won't cope with numbers larger
* than MAX_INT (2**32 on 32 bits arch)
*/
$serial = $this->x509_parsed['serialNumber'] . "";
$base = bcpow("2", "32");
$counter = 100;
$res = "";
$val = $serial;
while($counter > 0 && $val > 0) {
$counter = $counter - 1;
$tmpres = dechex(bcmod($val, $base)) . "";
/* adjust for 0's */
for ($i = 8-strlen($tmpres); $i > 0; $i = $i-1) {
$tmpres = "0$tmpres";
}
$res = $tmpres .$res;
$val = bcdiv($val, $base);
}
if ($counter <= 0) {
return false;
}
return strtoupper($res);
I don't have bcmath enabled so I cant test it at the moment.
You could use phpseclib for this purposes:
<?php
include('Math/BigInteger.php');
$cert_body = file_get_contents('mycert.crt');
$cert_decoded = openssl_x509_parse($cert_body, true);
echo $cert_decoded['serialNumber'] // outputs 5573199485241205751
$cert_serial = new Math_BigInteger($cert_decoded['serialNumber']);
$cert_serial = strtoupper($cert_serial->toHex());
echo $cert_serial // outputs B2A80498A3CEDC09
?>
精彩评论