Search code examples
phphexdecimalbigdecimalphpseclib

PHP convert large Decimal number to Hexadecimal


I am extracting information from a certificate using php and whilst the data is returned okay, there is one particular value "SerialNumber" which is being returned in what seems to be a different number format not sure what it is..

As an example, the actual format I am expecting to receive is:

‎58 ce a5 e3 63 51 b9 1f 49 e4 7a 20 ce ff 25 0f

However, what I am actually getting back is this:

118045041395046077749311747456482878735

Here is my php to perform the lookup:

$serial = $cert['tbsCertificate']['serialNumber'];

I have tried doing a few different conversions but none of them came back with the expected format.

Sample of a typical certificate serialnumber field..

enter image description here

VAR DUMP

    ["version"]=>
    string(2) "v3"
    ["serialNumber"]=>
    object(Math_BigInteger)#5 (6) {
      ["value"]=>
      string(39) "118045041395046077749311747456482878735"
      ["is_negative"]=>
      bool(false)
      ["generator"]=>
      string(7) "mt_rand"
      ["precision"]=>
      int(-1)
      ["bitmask"]=>
      bool(false)
      ["hex"]=>
      NULL

Solution

  • Your SerialNumber is a Math_BigInteger object as the var_dump shows. Use the toHex method to retrieve the contained number in a hexadecimal format. See reference on PEAR website.

    $serial = $cert['tbsCertificate']['serialNumber'];
    $valueInHex = $serial->toHex();
    

    Note: 118045041395046077749311747456482878735 in decimal format equals to 58CEA5E36351B91F49E47A20CEFF250F in hexadecimal format. You may easily check that with an online converter like this.