Completed
Push — master ( 7aa62b...6d63cb )
by Kirill
37:27
created

HasSignature::getValues()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 6
ccs 0
cts 5
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Personnage\Tinkoff\SDK\E2Card;
4
5
use function Personnage\Tinkoff\SDK\interpolate;
6
7
trait HasSignature
8
{
9
    /**
10
     * Transform array values to string.
11
     *
12
     * @param  array  $data
13
     * @return string
14
     */
15
    public static function getValues(array $data): string
16
    {
17
        ksort($data);
18
19
        return implode('', $data);
20
    }
21
22
    /**
23
     * Get message digest by GOST Р 34.11-94.
24
     *
25
     * @param string $values List arguments
26
     *
27
     * @return string
28
     */
29
    public static function digest(string $values): string
30
    {
31
        return hash('gost-crypto', $values, true);
32
    }
33
34
    /**
35
     * Calculate signature from digest message.
36
     *
37
     * @param  string  $digest
38
     * @param  string  $pemFile
39
     * @return string
40
     */
41
    public static function sign(string $digest, string $pemFile): string
42
    {
43
        $filename = function ($resource): string {
44
            return stream_get_meta_data($resource)['uri'];
45
        };
46
47
        fwrite($_ = tmpfile(), $digest);
48
49
        static $smime = <<<'CMD'
50
openssl smime -sign -signer %signer% -engine gost -gost89 -binary -noattr -nocerts -outform DER -in %in% -out %out%
51
CMD;
52
        shell_exec(interpolate($smime, [
53
            'in' => $filename($_),
54
            'out' => $filename($__ = tmpfile()),
55
            'signer' => $pemFile,
56
        ]));
57
58
        $output = shell_exec('openssl asn1parse -inform DER -in ' . $filename($__));
59
60
        return hex2bin(trim(substr($output, -129)));
61
    }
62
}
63