3 namespace Org\Mxchange\CoreFramework\Utils\Crypto;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
9 use \InvalidArgumentException;
13 * Crypto utilities class
15 * @author Roland Haeder <webmaster@shipsimu.org>
17 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2021 Core Developer Team
18 * @license GNU GPL 3.0 or any newer version
19 * @link http://www.shipsimu.org
21 * This program is free software: you can redistribute it and/or modify
22 * it under the terms of the GNU General Public License as published by
23 * the Free Software Foundation, either version 3 of the License, or
24 * (at your option) any later version.
26 * This program is distributed in the hope that it will be useful,
27 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 * GNU General Public License for more details.
31 * You should have received a copy of the GNU General Public License
32 * along with this program. If not, see <http://www.gnu.org/licenses/>.
34 final class CryptoUtils extends BaseFrameworkSystem {
36 * Length of output from hash()
38 private static $hashLength = NULL;
41 * Private constructor, no instance needed. If PHP would have a static initializer ...
45 private function __construct () {
46 // Call parent constructor
47 parent::__construct(__CLASS__);
51 * Hashes a given string with a simple but stronger hash function (no salt)
54 * @param $str The string to be hashed
55 * @return $hash The hash from string $str
56 * @throws InvalidArgumentException If a parameter is not valid
57 * @throws LogicException If proper extension ext-mhash is not loaded
59 public static final function hash (string $str) {
60 // Validate parameter/mhash extension
63 throw new InvalidArgumentException('Parameter "str" is empty');
64 } elseif (!extension_loaded('mhash')) {
66 throw new LogicException('Extension ext-mhash not loaded');
69 // Hash given string with (better secure) hasher
70 $hash = bin2hex(mhash(MHASH_SHA256, $str));
77 * "Getter" for length of hash() output. This will be "cached" to speed up
80 * @return $length Length of hash() output
82 public static final function getHashLength () {
84 if (is_null(self::$hashLength)) {
85 // No, then hash a string and save its length.
86 self::$hashLength = strlen(self::hash('abc123'));
90 return self::$hashLength;