Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env php
- <?php
- /**
- * Hash Tool
- * =========
- *
- * Small helper script to PHP's hash functions.
- *
- * @author Fabio Ros
- *
- * Examples:
- *
- * ./phash --adler32 somefile.txt
- * ./phash --sha256 mystring
- * ./phash --list
- *
- */
- /**
- * Class Hash
- */
- class Hash
- {
- public $arg;
- public $file;
- private $checkFileSize = 0;
- private $stringIfNotFile = 1;
- /**
- * Hash constructor.
- * @param $argv
- */
- public function __construct($argv)
- {
- if (!isset($argv[1])) {
- $this->outputHelp();
- } else {
- $this->parseOptions($argv);
- }
- if (isset($this->help) || $this->arg === 'help') {
- $this->outputHelp();
- exit();
- }
- if (isset($this->list)) {
- foreach (hash_algos() as $algo) {
- echo '* ' . $algo . "\n";
- }
- }
- if (isset($this->arg)) {
- $this->processFile();
- } else {
- // echo 'Specify some input for the algorithm';
- exit();
- }
- foreach (hash_algos() as $algo) {
- if (isset($this->$algo)) {
- $hash = hash($algo, $this->file);
- echo $hash;
- }
- }
- exit();
- }
- /**
- * Output help
- */
- public function outputHelp()
- {
- echo "PHP Hash tool\n";
- echo "================\n";
- echo "Usage:\n";
- echo "./phash --[options] [file/string]\n\n";
- echo "--list\tshow available algo's\n";
- echo "--algo\tRun file against a hash algorithm\n";
- }
- /**
- * Process the file with some validation
- */
- public function processFile()
- {
- if (substr($this->arg, 0, 2) === './') {
- $this->arg = str_replace('./', __DIR__ . DIRECTORY_SEPARATOR, $this->arg);
- }
- if (is_readable($this->arg)) {
- if (ini_get('memory_limit') !== '-1' && $this->checkFileSize) {
- $this->checkFileSizeWithMemory($this->arg);
- } else {
- $this->file = file_get_contents($this->arg);
- }
- } else {
- if ($this->stringIfNotFile) {
- $this->file = $this->arg;
- } else {
- echo 'File ' . $this->arg . 'is not readable.';
- exit();
- }
- }
- }
- /**
- * Check filesize with memory
- * @todo wip
- * @param $file
- * @return bool
- */
- public function checkFileSizeWithMemory($file)
- {
- $size = filesize($file) + memory_get_usage();
- if ($size <= intval(str_replace('M', '000', ini_get('memory_limit')))) {
- return true;
- } else {
- echo "File $file too big!\n";
- echo "Filesize:" . filesize($file) . "\n";
- echo "Memory Usage:" . memory_get_usage() . "\n";
- echo "Memory limit:" . ini_get('memory_limit') . "\n";
- }
- }
- /**
- * Parse arguments and options
- * @param $options
- */
- public function parseOptions($options)
- {
- array_shift($options);
- foreach ($options as $arg) {
- if (substr($arg, 0, 2) === '--') {
- if (strpos($arg, '=')) {
- $parsed = explode('=', str_replace('--', '', $arg))[0];
- $this->$parsed[0] = $parsed[1];
- } else {
- $parsed = str_replace('--', '', $arg);
- $this->$parsed = true;
- }
- } else {
- $this->arg = $arg;
- }
- }
- }
- }
- new Hash($argv);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement