简体   繁体   中英

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..

在此处输入图片说明

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

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 .

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM