Completed
Push — master ( eb2a5f...a1108e )
by Jan
02:54
created

CryptographyService::addWSESignature()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 12
cts 12
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 12
nc 1
nop 1
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 6
	public function __construct(string $privateKeyFile, string $publicKeyFile, string $privateKeyPassword = '')
18
	{
19 6
		$this->privateKeyFile = $privateKeyFile;
20 6
		$this->publicKeyFile = $publicKeyFile;
21 6
		$this->privateKeyPassword = $privateKeyPassword;
22 6
	}
23
24 3
	public function getPkpCode(array $body): string
25
	{
26
		$values = [
27 3
			$body['dic_popl'],
28 3
			$body['id_provoz'],
29 3
			$body['id_pokl'],
30 3
			$body['porad_cis'],
31 3
			$body['dat_trzby'],
32 3
			$body['celk_trzba'],
33
		];
34
35 3
		$plaintext = implode('|', $values);
36
37 3
		$privateKey = file_get_contents($this->privateKeyFile);
38 3
		$privateKeyId = openssl_pkey_get_private($privateKey, $this->privateKeyPassword);
39 3
		if ($privateKeyId === false) {
40 1
			throw new PrivateKeyFileException($this->privateKeyFile);
41
		}
42
43 2
		$ok = openssl_sign($plaintext, $signature, $privateKeyId, OPENSSL_ALGO_SHA256);
44 2
		if (!$ok) {
45 1
			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 3
	public function addWSESignature(string $request): string
61
	{
62 3
		$securityKey = new \RobRichards\XMLSecLibs\XMLSecurityKey(\RobRichards\XMLSecLibs\XMLSecurityKey::RSA_SHA256, ['type' => 'private']);
63 3
		$document = new \DOMDocument('1.0');
64 3
		$document->loadXML($request);
65 3
		$wse = new \RobRichards\WsePhp\WSSESoap($document);
66 3
		$securityKey->passphrase = $this->privateKeyPassword;
67 3
		$securityKey->loadKey($this->privateKeyFile, true);
68 3
		$wse->addTimestamp();
69 3
		$wse->signSoapDoc($securityKey, ['algorithm' => \RobRichards\XMLSecLibs\XMLSecurityDSig::SHA256]);
70 2
		$binaryToken = $wse->addBinaryToken(file_get_contents($this->publicKeyFile));
71 2
		$wse->attachTokentoSig($binaryToken);
72
73 2
		return $wse->saveXML();
74
	}
75
76
}
77