1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace rhertogh\Yii2SecurityTxt\helpers\GPG; |
4
|
|
|
|
5
|
|
|
use Crypt_GPG; |
6
|
|
|
use rhertogh\Yii2SecurityTxt\helpers\GPG\enums\GPGDriver; |
7
|
|
|
use rhertogh\Yii2SecurityTxt\helpers\GPG\traits\CryptGPGTrait; |
8
|
|
|
use rhertogh\Yii2SecurityTxt\helpers\GPG\traits\GnupgExtensionTrait; |
9
|
|
|
use yii\base\InvalidConfigException; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* A helper class for the GNU Privacy Guard. |
13
|
|
|
* It can run with either the Crypt_GPG package or the "gnupg" extension. |
14
|
|
|
* |
15
|
|
|
* @link https://packagist.org/packages/pear/crypt_gpg |
16
|
|
|
* @link https://www.php.net/manual/en/book.gnupg.php |
17
|
|
|
*/ |
18
|
|
|
class GPGHelper |
19
|
|
|
{ |
20
|
|
|
use CryptGPGTrait; |
21
|
|
|
use GnupgExtensionTrait; |
22
|
|
|
|
23
|
|
|
public static GPGDriver|null $driver = null; |
|
|
|
|
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Sign a message. |
27
|
|
|
* |
28
|
|
|
* @throws InvalidConfigException |
29
|
|
|
*/ |
30
|
|
|
public static function sign(string $message, string $privateKey): string |
31
|
|
|
{ |
32
|
|
|
$driver = static::$driver; |
33
|
|
|
|
34
|
|
|
if ( |
35
|
|
|
$driver === GPGDriver::CryptGPG |
36
|
|
|
|| $driver === null && class_exists(Crypt_GPG::class) |
37
|
|
|
) { |
38
|
|
|
$output = static::signViaCryptGPG($message, $privateKey); |
39
|
|
|
} elseif ( |
40
|
|
|
$driver === GPGDriver::GnupgExtension |
41
|
|
|
|| $driver === null && extension_loaded('gnupg') |
42
|
|
|
) { |
43
|
|
|
$output = static::signViaGnupgExtension($message, $privateKey); |
44
|
|
|
} else { |
45
|
|
|
throw new InvalidConfigException('Either the Crypt_GPG package (https://packagist.org/packages/pear/crypt_gpg)' |
46
|
|
|
. ' or the "gnupg" extension (https://www.php.net/manual/en/book.gnupg.php) must be installed.'); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
return $output; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* Verify a message. |
54
|
|
|
* |
55
|
|
|
* @throws InvalidConfigException |
56
|
|
|
*/ |
57
|
|
|
public static function verify(string $message, string $privateKey): string |
58
|
|
|
{ |
59
|
|
|
if (class_exists(Crypt_GPG::class)) { |
60
|
|
|
$output = static::signViaCryptGPG($message, $privateKey); |
61
|
|
|
} elseif (extension_loaded('gnupg')) { |
62
|
|
|
$output = static::signViaGnupgExtension($message, $privateKey); |
63
|
|
|
} else { |
64
|
|
|
throw new InvalidConfigException('Either the Crypt_GPG package (https://packagist.org/packages/pear/crypt_gpg)' |
65
|
|
|
. ' or the "gnupg" extension (https://www.php.net/manual/en/book.gnupg.php) must be installed.'); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
return $output; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|