Skip to content

Instantly share code, notes, and snippets.

@milankragujevic
Created September 18, 2017 19:46
Show Gist options
  • Save milankragujevic/9657e986b45cb852334d519e7788c0ed to your computer and use it in GitHub Desktop.
Save milankragujevic/9657e986b45cb852334d519e7788c0ed to your computer and use it in GitHub Desktop.
Convert Base32 text into Hexadecimal with PHP (useful for converting Torrent hashes i.e. vpr33qqm3l6bfu5fgozxmbnoraffszww => abe3bdc20cdafc12d3a533b37605ae880a5966d6)
<?php
function mk_base32_to_hex($input) {
$map = array(
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', '2', '3', '4', '5', '6', '7',
'='
);
$flippedMap = array(
'A'=>'0', 'B'=>'1', 'C'=>'2', 'D'=>'3', 'E'=>'4', 'F'=>'5', 'G'=>'6', 'H'=>'7',
'I'=>'8', 'J'=>'9', 'K'=>'10', 'L'=>'11', 'M'=>'12', 'N'=>'13', 'O'=>'14', 'P'=>'15',
'Q'=>'16', 'R'=>'17', 'S'=>'18', 'T'=>'19', 'U'=>'20', 'V'=>'21', 'W'=>'22', 'X'=>'23',
'Y'=>'24', 'Z'=>'25', '2'=>'26', '3'=>'27', '4'=>'28', '5'=>'29', '6'=>'30', '7'=>'31'
);
if(empty($input)) return;
$paddingCharCount = substr_count($input, $map[32]);
$allowedValues = array(6,4,3,1,0);
if(!in_array($paddingCharCount, $allowedValues)) return false;
for($i=0; $i<4; $i++){
if($paddingCharCount == $allowedValues[$i] &&
substr($input, -($allowedValues[$i])) != str_repeat($map[32], $allowedValues[$i])) return false;
}
$input = str_replace('=','', $input);
$input = str_split($input);
$binaryString = "";
for($i=0; $i < count($input); $i = $i+8) {
$x = "";
if(!in_array($input[$i], $map)) return false;
for($j=0; $j < 8; $j++) {
$x .= str_pad(base_convert($flippedMap[$input[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT);
}
$eightBits = str_split($x, 8);
for($z = 0; $z < count($eightBits); $z++) {
$binaryString .= ( ($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48 ) ? $y:"";
}
}
$hexString2 = strtolower(bin2hex($binaryString));
return $hexString2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment