diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..57872d0 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/vendor/ diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..fb3699f --- /dev/null +++ b/composer.json @@ -0,0 +1,12 @@ +{ + "name": "kvazar/crypto", + "description": "Crypto Tools for PHP 8", + "type": "library", + "license": "MIT", + "autoload": { + "psr-4": { + "Kvazar\\Crypto\\": "src/" + } + }, + "require": {} +} diff --git a/src/Base58.php b/src/Base58.php new file mode 100644 index 0000000..d015fd7 --- /dev/null +++ b/src/Base58.php @@ -0,0 +1,123 @@ + 256) + { + return null; + } + + bcscale(0); + + $value = ''; + + if (!$digits) + { + $digits = self::digits( + $base + ); + } + + while ($dec > $base - 1) + { + $rest = bcmod( + $dec, + $base + ); + + $dec = bcdiv( + $dec, + $base + ); + + $value = $digits[$rest] . $value; + } + + $value = $digits[intval($dec)] . $value; + + return (string) $value; + } + + public static function base2dec($value, $base, $digits = false): ?string + { + if ($base < 2 || $base > 256) + { + return null; + } + + bcscale(0); + + if ($base < 37) + { + $value = strtolower( + $value + ); + } + + if (!$digits) + { + $digits = self::digits( + $base + ); + } + + $size = strlen( + $value + ); + + $dec = '0'; + + for ($loop = 0; $loop < $size; $loop++) + { + $element = strpos( + $digits, + $value[$loop] + ); + + $power = bcpow( + $base, + $size - $loop - 1 + ); + + $dec = bcadd( + $dec, + bcmul( + $element, + $power + ) + ); + } + + return (string) $dec; + } + + public static function digits($base): string + { + if ($base > 64) + { + $digits = ''; + + for ($loop = 0; $loop < 256; $loop++) + { + $digits .= chr( + $loop + ); + } + } + + else + { + $digits = '0123456789abcdefghijklmnopqrstuvwxyz'; + $digits .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ-_'; + } + + $digits = substr( + $digits, 0, $base + ); + + return (string) $digits; + } + + public static function bin2bc($num) + { + return self::base2dec( + $num, + 256 + ); + } +} \ No newline at end of file