user3436467
user3436467

Reputation: 1775

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

Upvotes: 2

Views: 1708

Answers (2)

Madan Sapkota
Madan Sapkota

Reputation: 26071

Here is alternative solution to convert decimal number to hexadecimal format without using external libraries.

$dec = '118045041395046077749311747456482878735';
// init hex array
$hex = array();

while ($dec) {
    // get modulus // based on docs both params are string
    $modulus = bcmod($dec, '16');
    // convert to hex and prepend to array
    array_unshift($hex, dechex($modulus));
    // update decimal number
    $dec = bcdiv(bcsub($dec, $modulus), 16);
}

// array elements to string
echo implode('', $hex);

And the output of the code ... Online Demo

58cea5e36351b91f49e47a20ceff250f

You can also use string concatenation instead of array prepend. Hope this helps. Thanks!

Upvotes: 0

mcserep
mcserep

Reputation: 3299

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.

Upvotes: 4

Related Questions