Completed
Pull Request — master (#3)
by
unknown
03:12
created

CryptographyService::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 3
crap 1
1
<?php declare(strict_types = 1);
2
3
namespace SlevomatEET\Cryptography;
4
5
class CryptographyService
6
{
7
8
	/** @var string */
9
	private $privateKeyFile;
10
11
	/** @var string */
12
	private $privateKeyPassword;
13
14
	/** @var string */
15
	private $publicKeyFile;
16
17 2
	public function __construct(string $privateKeyFile, string $publicKeyFile, string $privateKeyPassword = '')
18
	{
19 2
		$this->privateKeyFile = $privateKeyFile;
20 2
		$this->publicKeyFile = $publicKeyFile;
21 2
		$this->privateKeyPassword = $privateKeyPassword;
22 2
	}
23
24 1
	public function getPkpCode(array $body): string
25
	{
26
		$values = [
27 1
			$body['dic_popl'],
28 1
			$body['id_provoz'],
29 1
			$body['id_pokl'],
30 1
			$body['porad_cis'],
31 1
			$body['dat_trzby'],
32 1
			$body['celk_trzba'],
33
		];
34
35 1
		$plaintext = implode('|', $values);
36
37 1
		$privateKey = file_get_contents($this->privateKeyFile);
38 1
		$privateKeyId = openssl_pkey_get_private($privateKey, $this->privateKeyPassword);
39 1
		if ($privateKeyId === false) {
40
			throw new PrivateKeyFileException($this->privateKeyFile);
41
		}
42
43 1
		$ok = openssl_sign($plaintext, $signature, $privateKeyId, OPENSSL_ALGO_SHA256);
44 1
		if (!$ok) {
45
			throw new SigningFailedException($values);
46
		}
47
48 1
		openssl_free_key($privateKeyId);
49
50 1
		return $signature;
51
	}
52
53 1
	public function getBkpCode(string $pkpCode): string
54
	{
55 1
		$bkp = strtoupper(sha1($pkpCode));
56
57 1
		return implode('-', str_split($bkp, 8));
58
	}
59
60 1
	public function addWSESignature(string $request): string
61
	{
62 1
		$securityKey = new \RobRichards\XMLSecLibs\XMLSecurityKey(\RobRichards\XMLSecLibs\XMLSecurityKey::RSA_SHA256, ['type' => 'private']);
63 1
		$document = new \DOMDocument('1.0');
64 1
		$document->loadXML($request);
65 1
		$wse = new \RobRichards\WsePhp\WSSESoap($document);
66 1
		$securityKey->passphrase = $this->privateKeyPassword;
67 1
		$securityKey->loadKey($this->privateKeyFile, true);
68 1
		$wse->addTimestamp();
69 1
		$wse->signSoapDoc($securityKey, ['algorithm' => \RobRichards\XMLSecLibs\XMLSecurityDSig::SHA256]);
70 1
		$binaryToken = $wse->addBinaryToken(file_get_contents($this->publicKeyFile));
71 1
		$wse->attachTokentoSig($binaryToken);
72
73 1
		return $wse->saveXML();
74
	}
75
76
}
77