-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sha256.php
72 lines (63 loc) · 1.61 KB
/
Sha256.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
namespace VaasSdk;
use VaasSdk\Exceptions\FileDoesNotExistException;
use VaasSdk\Exceptions\InvalidSha256Exception;
class Sha256
{
private string $_hash;
/**
* Gets Sha256 from file
*
* @param string $path the path of the file to hash
*
* @return Sha256
*/
public static function TryFromFile(string $path): Sha256
{
if (!file_exists($path)) {
throw new FileDoesNotExistException();
}
$hashString = hash_file("sha256", $path);
if (Sha256::IsValid($hashString)) {
$sha256 = new Sha256();
$sha256->_hash = $hashString;
return $sha256;
}
throw new InvalidSha256Exception();
}
/**
* Gets Sha256 from string
*
* @param string $hashString the string to create the hash from
*
* @return Sha256
*/
public static function TryFromString(string $hashString): Sha256
{
if (Sha256::IsValid($hashString)) {
$sha256 = new Sha256();
$sha256->_hash = $hashString;
return $sha256;
}
throw new InvalidSha256Exception();
}
/**
* Validates a hash to be a valid sha256
*
* @param string $hash the string to validate
*
* @return bool returns true if sha256 is valid
*/
public static function IsValid(string $hash): bool
{
if (preg_match("/^([a-f0-9]{64})$/", strtolower($hash)) == 1) {
return true;
} else {
return false;
}
}
public function __toString(): string
{
return $this->_hash;
}
}