-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSha256.php
79 lines (68 loc) · 2.16 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
73
74
75
76
77
78
79
<?php
namespace VaasSdk;
use Amp\Future;
use VaasSdk\Exceptions\FileDoesNotExistException;
use VaasSdk\Exceptions\InvalidSha256Exception;
use function Amp\async;
class Sha256
{
private string $_hash;
/**
* Gets Sha256 from file
* @param string $path the path of the file to hash
* @return Future that resolves as the sha256 object
* @throws FileDoesNotExistException if the file does not exist
* @throws InvalidSha256Exception if the hash is invalid
*/
public static function TryFromFile(string $path): Future
{
return async(function () use ($path) {
if (!file_exists($path)) {
throw new FileDoesNotExistException();
}
$hashString = hash_file("sha256", $path);
if (Sha256::IsValid($hashString)->await()) {
$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 Future that resolves to the sha256 object
* @throws InvalidSha256Exception if the hash is invalid
*/
public static function TryFromString(string $hashString): Future
{
return async(function () use($hashString) {
if (Sha256::IsValid($hashString)->await()) {
$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 Future that resolves as true if sha256 is valid
*/
public static function IsValid(string $hash): Future
{
return async(function () use ($hash) {
if (preg_match("/^([a-f0-9]{64})$/", strtolower($hash)) == 1) {
return true;
} else {
return false;
}
});
}
public function __toString(): string
{
return $this->_hash;
}
}