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

HasSignature   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 0
loc 56
ccs 0
cts 26
cp 0
rs 10
c 0
b 0
f 0
wmc 3
lcom 0
cbo 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getValues() 0 6 1
A digest() 0 4 1
A sign() 0 21 1
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