Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- const B16_STR = '0123456789abcdef';
- const B36_STR = '0123456789abcdefghijklmnopqrstuvwxyz';
- const B64_STR = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-';
- function gcd($a,$b){
- return ($a%$b)?gcd($b,$a%$b):$b;
- }
- function convert($str, $from, $to){
- $len_from = strlen($from);
- $len_to = strlen($to);
- if(!preg_match('/^['.$from.']+$/'.(preg_match('/^([^[:upper:]]*|[^[:lower:]]*)(?1)*(?!\1)$/', $from)?'':'i'),$str)
- || $len_from<=0 || $len_to<=0){
- throw new Exception();
- }
- $buf = [];
- $offset = 0;
- $l = strlen($str);
- $c = 0;
- $bits_from;$bits_to;
- $segs_from;$segs_to;
- {
- $log2 = log(2);
- $bits_from = log($len_from)/$log2;
- $bits_to = log($len_to)/$log2;
- $lcm = $bits_from*$bits_to/gcd($bits_from,$bits_to);
- $segs_from = $lcm / $bits_from;
- $segs_to = $lcm / $bits_to;
- }
- while($offset<$l){
- for($j=0;$j<$segs_from;$j++){
- $c |= strpos($from, $str[($offset<$l)?$offset++:0])<<($bits_from*$j);
- }
- for($i=0;$i<$segs_to;$i++){
- array_push($buf, $to[($c>>($i*$bits_to))&($len_to-1)]);
- }
- $c = 0;
- }
- return implode($buf);
- }
- function hex64($str){
- return convert($str, B16_STR, B64_STR);
- }
- function hex64r($str){
- return convert($str, B64_STR, B16_STR);
- }
- function convertTest($TEST_COUNT = 1000000){
- $failed = 0;
- for($i=0;$i<$TEST_COUNT;$i++){
- $h = hash('whirlpool', 'a'.rand());
- $t = substr(hex64r(hex64($h)),0,strlen($h));
- if(!$h===$t){
- echo $h,"\n<br>",$t,"\n<br>\n<br>";
- $failed++;
- }
- }
- echo 'Passed ',$TEST_COUNT-$failed,' out of ',$TEST_COUNT;
- }
- convertTest(1000);
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement