|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace rhertogh\Yii2SecurityTxt\helpers\GPG\traits; |
|
4
|
|
|
|
|
5
|
|
|
use Crypt_GPG; |
|
6
|
|
|
use Crypt_GPG_Exception; |
|
7
|
|
|
use Crypt_GPG_KeyNotFoundException; |
|
8
|
|
|
use Crypt_GPG_Signature; |
|
9
|
|
|
use PEAR_Exception; |
|
10
|
|
|
use Yii; |
|
11
|
|
|
use yii\helpers\FileHelper; |
|
12
|
|
|
|
|
13
|
|
|
trait CryptGPGTrait |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* @throws Crypt_GPG_Exception |
|
17
|
|
|
* @throws PEAR_Exception |
|
18
|
|
|
*/ |
|
19
|
2 |
|
protected static function signViaCryptGPG(string $message, string $privateKey): string |
|
20
|
|
|
{ |
|
21
|
2 |
|
Yii::beginProfile('Generate PGP signature', __METHOD__); |
|
22
|
2 |
|
$gpg = static::getCryptGpg($gnupgHome); |
|
23
|
|
|
try { |
|
24
|
2 |
|
$keyInfo = $gpg->importKey($privateKey); |
|
25
|
2 |
|
$gpg->addSignKey($keyInfo['fingerprint']); |
|
26
|
2 |
|
$output = $gpg->sign($message, Crypt_GPG::SIGN_MODE_CLEAR); |
|
27
|
|
|
} finally { |
|
28
|
2 |
|
FileHelper::removeDirectory($gnupgHome); |
|
29
|
|
|
} |
|
30
|
2 |
|
Yii::endProfile('Generate PGP signature', __METHOD__); |
|
31
|
2 |
|
return $output; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* @throws Crypt_GPG_Exception |
|
36
|
|
|
* @throws PEAR_Exception |
|
37
|
|
|
*/ |
|
38
|
2 |
|
protected static function verifyViaCryptGPG(string $message, string $publicKey): string|false |
|
39
|
|
|
{ |
|
40
|
2 |
|
Yii::beginProfile('Verify PGP signature', __METHOD__); |
|
41
|
2 |
|
$gpg = static::getCryptGpg($gnupgHome); |
|
42
|
|
|
try { |
|
43
|
2 |
|
$keyInfo = $gpg->importKey($publicKey); |
|
44
|
2 |
|
$gpg->addEncryptKey($keyInfo['fingerprint']); |
|
45
|
|
|
/** @var array{ |
|
46
|
|
|
* data: string, |
|
47
|
|
|
* signatures: Crypt_GPG_Signature[], |
|
48
|
|
|
* } $info |
|
49
|
|
|
*/ |
|
50
|
2 |
|
$info = $gpg->decryptAndVerify($message); |
|
51
|
2 |
|
} catch (Crypt_GPG_KeyNotFoundException) { |
|
52
|
2 |
|
return false; |
|
53
|
|
|
} finally { |
|
54
|
2 |
|
FileHelper::removeDirectory($gnupgHome); |
|
55
|
|
|
} |
|
56
|
2 |
|
if (!$info['signatures'][0]->isValid()) { |
|
57
|
|
|
return false; |
|
58
|
|
|
} |
|
59
|
2 |
|
Yii::endProfile('Verify PGP signature', __METHOD__); |
|
60
|
2 |
|
return $info['data']; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
2 |
|
protected static function getCryptGpg(&$gnupgHome = null): Crypt_GPG |
|
64
|
|
|
{ |
|
65
|
2 |
|
if (empty($gnupgHome)) { |
|
66
|
2 |
|
$gnupgHome = Yii::getAlias('@runtime') . '/gnupg/' . uniqid(more_entropy: true); |
|
|
|
|
|
|
67
|
2 |
|
FileHelper::createDirectory($gnupgHome); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
2 |
|
return new Crypt_GPG(['homedir' => $gnupgHome]); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|