From 6c6bf6fe589285efaf8d66ae29bf2c12a1990365 Mon Sep 17 00:00:00 2001
From: =?utf8?q?Roland=20H=C3=A4der?= <roland@mxchange.org>
Date: Sun, 17 Jan 2021 05:54:29 +0100
Subject: [PATCH] Continued: - added hash-benchmark.php; previous in "hub"
 project aka. mhash-benchmark.php,   but since ext-mash is replaced by Hash,
 this needs porting, too. - "new" array style [] used in audio.php - ported
 CryptoUtils::hash() to PHP's new Hash "extension" - Minor improvements
MIME-Version: 1.0
Content-Type: text/plain; charset=utf8
Content-Transfer-Encoding: 8bit

Signed-off-by: Roland Häder <roland@mxchange.org>
---
 contrib/audio.php                             |  6 ++--
 contrib/hash-benchmark.php                    | 32 +++++++++++++++++++
 .../index/file/stack/class_FileStackIndex.php |  2 +-
 .../stacker/file/class_BaseFileStack.php      |  4 +--
 .../utils/crypto/class_CryptoUtils.php        | 10 +++---
 5 files changed, 44 insertions(+), 10 deletions(-)
 create mode 100755 contrib/hash-benchmark.php

diff --git a/contrib/audio.php b/contrib/audio.php
index 3bf11ac5..40508f14 100644
--- a/contrib/audio.php
+++ b/contrib/audio.php
@@ -1,11 +1,11 @@
 <?php
-$GLOBALS['options'] = array(
+$GLOBALS['options'] = [
 	'analyze_input' => FALSE,
 	'reduce_noise'  => FALSE,
 	'ignore_noise'  => FALSE,
 	'keep_noise'    => FALSE,
 	'buffer_size'   => 8,
-);
+];
 
 if (isset($_SERVER['argv'][1]) && $_SERVER['argv'][1] == 'a') {
 	$GLOBALS['options']['analyze_input'] = TRUE;
@@ -24,7 +24,7 @@ if (isset($_SERVER['argv'][1]) && $_SERVER['argv'][1] == 'i') {
 }
 
 function analyzeForNoiseOnly ($data) {
-	$GLOBALS['analysis']['breakdown'] = array();
+	$GLOBALS['analysis']['breakdown'] = [];
 	$GLOBALS['analysis']['average']   = 0;
 
 	for ($i = 0; $i < strlen($data); $i++) {
diff --git a/contrib/hash-benchmark.php b/contrib/hash-benchmark.php
new file mode 100755
index 00000000..8a10f0c2
--- /dev/null
+++ b/contrib/hash-benchmark.php
@@ -0,0 +1,32 @@
+#!/usr/bin/env php
+<?php
+error_reporting(0);
+set_time_limit(0);
+
+/*
+ * Note: I could use mhash_count() here but I like to see unavailable hashers
+ * because this is important to me to choose the most-available hasher(s) and
+ * those with the best speed/secure tradeoff.
+ */
+$hasher = hash_algos();
+
+$timers = array();
+$count = 500 * 1000;
+
+print 'Iterating ' . $count . 'x over all ' . count($hasher) . ' hash functions ...' . "\r\n";
+
+foreach ($hasher as $hash) {
+	$time = microtime(true);
+	for ($idx = 0; $idx <= $count; $idx++) {
+		$dummy = hash($hash, 'hash-test-abc-123-foo-bar');
+	}
+
+	$timers[$hash] = (microtime(true) - $time);
+	print '.';
+}
+
+print "\r\n\r\n";
+asort($timers);
+
+print 'Result from hash() benchmark (in seconds per hasher):' . "\r\n";
+print_r($timers) . "\n";
diff --git a/framework/main/classes/index/file/stack/class_FileStackIndex.php b/framework/main/classes/index/file/stack/class_FileStackIndex.php
index 517a9368..4c91d818 100644
--- a/framework/main/classes/index/file/stack/class_FileStackIndex.php
+++ b/framework/main/classes/index/file/stack/class_FileStackIndex.php
@@ -99,7 +99,7 @@ class FileStackIndex extends BaseFileIndex implements IndexableStack, Registerab
 		$rawData = sprintf('%s%s%s%s%s%s%s',
 			$stackName,
 			Indexable::SEPARATOR_GROUP_HASH,
-			hex2bin($data[StackableFile::ARRAY_NAME_HASH]),
+			$data[StackableFile::ARRAY_NAME_HASH],
 			Indexable::SEPARATOR_HASH_GAP_POSITION,
 			$data[StackableFile::ARRAY_NAME_GAP_POSITION],
 			Indexable::SEPARATOR_GAP_LENGTH,
diff --git a/framework/main/classes/stacker/file/class_BaseFileStack.php b/framework/main/classes/stacker/file/class_BaseFileStack.php
index f904afb5..8a81139a 100644
--- a/framework/main/classes/stacker/file/class_BaseFileStack.php
+++ b/framework/main/classes/stacker/file/class_BaseFileStack.php
@@ -282,7 +282,7 @@ abstract class BaseFileStack extends BaseStacker {
 		/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: Calling this->readStackHeader() ...');
 		$this->readStackHeader();
 
-		// Is the index loaded correctly and the stack file is just created?
+		// Is the index loaded correctly, e.g. the stack file is just created?
 		/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: Calling this->indexInstance->isIndexLoaded() ...');
 		if (!$this->getIndexInstance()->isIndexLoaded()) {
 			/*
@@ -712,7 +712,7 @@ abstract class BaseFileStack extends BaseStacker {
 		$rawData = sprintf('%s%s%s%s%s',
 			$stackName,
 			BinaryFile::SEPARATOR_GROUP_HASH,
-			hex2bin($hash),
+			$hash,
 			BinaryFile::SEPARATOR_HASH_VALUE,
 			$encoded
 		);
diff --git a/framework/main/classes/utils/crypto/class_CryptoUtils.php b/framework/main/classes/utils/crypto/class_CryptoUtils.php
index 3677b4e4..99254d13 100644
--- a/framework/main/classes/utils/crypto/class_CryptoUtils.php
+++ b/framework/main/classes/utils/crypto/class_CryptoUtils.php
@@ -54,22 +54,24 @@ final class CryptoUtils extends BaseFrameworkSystem {
 	 * @param	$str	The string to be hashed
 	 * @return	$hash	The hash from string $str
 	 * @throws	InvalidArgumentException	If a parameter is not valid
-	 * @throws	LogicException	If proper extension ext-mhash is not loaded
+	 * @throws	LogicException	If proper extension hash is not loaded
 	 */
 	public static final function hash (string $str) {
 		// Validate parameter/mhash extension
+		/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CRYPTO-UTILS: str=%s - CALLED!', $str));
 		if (empty($str)) {
 			// Throw IAE
 			throw new InvalidArgumentException('Parameter "str" is empty');
-		} elseif (!extension_loaded('mhash')) {
+		} elseif (!extension_loaded('hash')) {
 			// Should be there
-			throw new LogicException('Extension ext-mhash not loaded');
+			throw new LogicException('Extension ext-hash not loaded');
 		}
 
 		// Hash given string with (better secure) hasher
-		$hash = bin2hex(mhash(MHASH_SHA256, $str));
+		$hash = hash('sha256', $str, true);
 
 		// Return it
+		/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CRYPTO-UTILS: hash(%d){}=%s - EXIT!', strlen($hash), bin2hex($hash)));
 		return $hash;
 	}
 
-- 
2.39.5