1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace rhertogh\Yii2SecurityTxt\helpers\GPG\traits; |
4
|
|
|
|
5
|
|
|
use gnupg; |
6
|
|
|
use Yii; |
7
|
|
|
use yii\base\InvalidConfigException; |
8
|
|
|
|
9
|
|
|
trait GnupgExtensionTrait |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @throws InvalidConfigException |
13
|
|
|
*/ |
14
|
|
|
protected static function signViaGnupgExtension($message, $privateKey) |
15
|
|
|
{ |
16
|
|
|
Yii::beginProfile('Generate PGP signature', __METHOD__); |
17
|
|
|
$gpg = new gnupg(); |
18
|
|
|
$gpg->seterrormode(GNUPG_ERROR_EXCEPTION); |
19
|
|
|
|
20
|
|
|
$keyInfo = $gpg->import($privateKey); |
21
|
|
|
if ($keyInfo === false) { |
22
|
|
|
throw new InvalidConfigException('Unable to import private key. Debug info: ' |
23
|
|
|
. var_export(static::generateGnupgDebugInfo($gpg), true)); |
24
|
|
|
} |
25
|
|
|
$gpg->addsignkey($keyInfo['fingerprint']); |
26
|
|
|
$gpg->setsignmode(gnupg::SIG_MODE_CLEAR); |
|
|
|
|
27
|
|
|
$output = $gpg->sign($message); |
28
|
|
|
if ($output === false) { |
29
|
|
|
throw new InvalidConfigException('Unable to sign the message. Debug info: ' |
30
|
|
|
. var_export(static::generateGnupgDebugInfo($gpg), true)); |
31
|
|
|
} |
32
|
|
|
Yii::endProfile('Generate PGP signature', __METHOD__); |
33
|
|
|
return $output; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
protected static function generateGnupgDebugInfo(gnupg $gpg) |
37
|
|
|
{ |
38
|
|
|
$debugInfo = [ |
39
|
|
|
'engineInfo' => $gpg->getengineinfo(), |
|
|
|
|
40
|
|
|
'errorInfo' => $gpg->geterrorinfo(), |
|
|
|
|
41
|
|
|
]; |
42
|
|
|
|
43
|
|
|
if (empty($debugInfo['engineInfo']['home_dir'])) { |
44
|
|
|
$debugInfo['hint'] = 'The gnupg home directory is not set, it can be set via the GNUPGHOME environment variable.'; |
45
|
|
|
} elseif (!is_writable($debugInfo['engineInfo']['home_dir'])) { |
46
|
|
|
$debugInfo['hint'] = 'The gnupg home directory (' . $debugInfo['engineInfo']['home_dir'] . ') might not be writable. ' |
47
|
|
|
. 'Hint: can be changed via the GNUPGHOME environment variable.'; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
return $debugInfo; |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|