/
OpensslCli.php
74 lines (60 loc) · 1.96 KB
/
OpensslCli.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
<?php
namespace Ekapusta\OAuth2Esia\Security\Signer;
use Ekapusta\OAuth2Esia\Security\Signer;
use Ekapusta\OAuth2Esia\Security\Signer\Exception\SignException;
class OpensslCli extends Signer
{
private $toolPath;
private $middleParams;
public function __construct(
$certificatePath,
$privateKeyPath,
$privateKeyPassword = null,
$toolPath = 'openssl'
) {
parent::__construct($certificatePath, $privateKeyPath, $privateKeyPassword);
if (is_array($toolPath) && count($toolPath) == 2) {
$this->middleParams = end($toolPath);
$toolPath = reset($toolPath);
}
$this->toolPath = $toolPath;
}
public function sign($message)
{
return $this->runParameters([
'smime -sign -binary -outform DER -noattr',
$this->middleParams,
'-signer '.escapeshellarg($this->certificatePath),
'-inkey '.escapeshellarg($this->privateKeyPath),
'-passin '.escapeshellarg('pass:'.$this->privateKeyPassword),
], $message);
}
private function runParameters(array $parameters, $input)
{
array_unshift($parameters, $this->toolPath);
return $this->run(implode(' ', $parameters), $input);
}
/**
* Runs command with input from STDIN.
*/
private function run($command, $input)
{
$process = proc_open($command, [
['pipe', 'r'], // stdin
['pipe', 'w'], // stdout
['pipe', 'w'], // stderr
], $pipes);
fwrite($pipes[0], $input);
fclose($pipes[0]);
$result = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$errors = stream_get_contents($pipes[2]);
fclose($pipes[2]);
$code = proc_close($process);
if (0 != $code) {
$errors = trim($errors) ?: 'unknown';
throw SignException::signFailedAsOf($errors, $code);
}
return $result;
}
}