| 1 |
<?php |
| 2 |
/** |
| 3 |
* Handles hashing operations for Altcha. |
| 4 |
* |
| 5 |
* @package WP_Defender\Component\Altcha\Hasher |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace WP_Defender\Component\Altcha\Hasher; |
| 9 |
|
| 10 |
/** |
| 11 |
* Class Hasher |
| 12 |
*/ |
| 13 |
class Hasher implements HasherInterface { |
| 14 |
/** |
| 15 |
* Hashes the given data using the specified algorithm. |
| 16 |
* |
| 17 |
* @param string $algorithm The hashing algorithm to use. |
| 18 |
* @param string $data The data to hash. |
| 19 |
* |
| 20 |
* @return string The hashed data. |
| 21 |
*/ |
| 22 |
public function hash( string $algorithm, string $data ): string { |
| 23 |
return match ( $algorithm ) { |
| 24 |
Algorithm::SHA1 => sha1( $data, true ), |
| 25 |
Algorithm::SHA256 => hash( 'sha256', $data, true ), |
| 26 |
Algorithm::SHA512 => hash( 'sha512', $data, true ), |
| 27 |
}; |
| 28 |
} |
| 29 |
|
| 30 |
/** |
| 31 |
* Hashes the given data using the specified algorithm and returns the hash in hexadecimal format. |
| 32 |
* |
| 33 |
* @param string $algorithm The hashing algorithm to use. |
| 34 |
* @param string $data The data to hash. |
| 35 |
* |
| 36 |
* @return string The hashed data in hexadecimal format. |
| 37 |
*/ |
| 38 |
public function hash_hex( string $algorithm, string $data ): string { |
| 39 |
return bin2hex( $this->hash( $algorithm, $data ) ); |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* Hashes the given data using HMAC with the specified algorithm and HMAC key. |
| 44 |
* |
| 45 |
* @param string $algorithm The hashing algorithm to use. |
| 46 |
* @param string $data The data to hash. |
| 47 |
* @param string $hmac_key The HMAC key to use. |
| 48 |
* |
| 49 |
* @return string The HMAC hashed data. |
| 50 |
*/ |
| 51 |
public function hash_hmac( string $algorithm, string $data, string $hmac_key ): string { |
| 52 |
return match ( $algorithm ) { |
| 53 |
Algorithm::SHA1 => hash_hmac( 'sha1', $data, $hmac_key, true ), |
| 54 |
Algorithm::SHA256 => hash_hmac( 'sha256', $data, $hmac_key, true ), |
| 55 |
Algorithm::SHA512 => hash_hmac( 'sha512', $data, $hmac_key, true ), |
| 56 |
}; |
| 57 |
} |
| 58 |
|
| 59 |
/** |
| 60 |
* Hashes the given data using HMAC with the specified algorithm and HMAC key, returning the hash in hexadecimal format. |
| 61 |
* |
| 62 |
* @param string $algorithm The hashing algorithm to use. |
| 63 |
* @param string $data The data to hash. |
| 64 |
* @param string $hmac_key The HMAC key to use. |
| 65 |
* |
| 66 |
* @return string The HMAC hashed data in hexadecimal format. |
| 67 |
*/ |
| 68 |
public function hash_hmac_hex( string $algorithm, string $data, string $hmac_key ): string { |
| 69 |
return bin2hex( $this->hash_hmac( $algorithm, $data, $hmac_key ) ); |
| 70 |
} |
| 71 |
} |
| 72 |
|