PHP Convert Hext To Base32 And Vice Versa

908 views Asked by At

I am facing problem to convert a hex representation to base 32 and vice versa.

all online convert is JavaScript based, but i can't find any PHP based solution after quite search here and there :(

i have tried base32Encode the hex value, hexdec then base32 encode none of them work actually :(

hex: 686aa8fca1767a5c1cc23b0f982380d6ba6d07ff32fafe8e

base32: NBVKR7FBOZ5FYHGCHMHZQI4A225G2B77GL5P5DQ

what i need here, i need to get (convert) the base32 value from the hex value and vice versa like get the hex value from the base 32.

that's all

Update 1:

following site can encode from hex to base32 in a way what exactly i am looking for but. but i don't know how they do it.. :(

screenshot: enter image description here

thanks

2

There are 2 answers

1
nosurs On BEST ANSWER

The library suggested by Sammitch works fine (it's RFC 4648 compliant like the site you've posted), but you'll need to add hex2bin()/bin2hex() into the mix to get the results you're after:

require 'path/to/vendor/autoload.php';

use Base32\Base32;

$hex = '686aa8fca1767a5c1cc23b0f982380d6ba6d07ff32fafe8e';

// Hex to Base32

$to_base32 = Base32::encode(hex2bin($hex)); 
var_dump($to_base32); // NBVKR7FBOZ5FYHGCHMHZQI4A225G2B77GL5P5DQ=

// Base32 to Hex

$to_hex = bin2hex(Base32::decode($to_base32));
var_dump($to_hex); // 686aa8fca1767a5c1cc23b0f982380d6ba6d07ff32fafe8e
1
Sammitch On

Assuming that you meant base36 instead of base32:

$in16 = '686aa8fca1767a5c1cc23b0f982380d6ba6d07ff32fafe8e';
$in36 = 'NBVKR7FBOZ5FYHGCHMHZQI4A225G2B77GL5P5DQ';

var_dump(
    base_convert($in16, 16, 32),
    base_convert($in36, 36, 16)
);

Output:

string(39) "1k6la7sk5r7o000000000000000000000000000"
string(51) "200727aed64d340000000000000000000000000000000000000"

All those zeroes at the end, smells like cryptocurrency.