Test Failed
Push — feature/post-pay ( e3663d...906e88 )
by Remco
04:22
created

Security::get_signature_fields_combined()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 2
ccs 1
cts 1
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Security
4
 *
5
 * @author    Pronamic <[email protected]>
6
 * @copyright 2005-2018 Pronamic
7
 * @license   GPL-3.0-or-later
8
 * @package   Pronamic\WordPress\Pay\Gateways\OmniKassa2
9
 */
10
11
namespace Pronamic\WordPress\Pay\Gateways\OmniKassa2;
12
13
/**
14
 * Security
15
 *
16
 * @author  Remco Tolsma
17
 * @version 2.0.2
18
 * @since   1.0.0
19
 */
20
class Security {
21
	/**
22
	 * Get signature fields combined.
23
	 *
24
	 * @param array $fields Fields.
25
	 * @return string
26
	 */
27
	public static function get_signature_fields_combined( $fields ) {
28 4
		return implode( ',', $fields );
29 4
	}
30
31 4
	/**
32
	 * Calculdate signature for specific data.
33
	 *
34
	 * @param Signable $signable    Signable object.
35 4
	 * @param string   $signing_key Signing Key.
36
	 * @return string|null
37
	 */
38
	public static function get_signature( Signable $signable, $signing_key ) {
39 4
		$fields = $signable->get_signature_fields();
40
41 4
		if ( empty( $fields ) ) {
42
			return null;
43
		}
44
45 4
		if ( empty( $signing_key ) ) {
46
			return null;
47 4
		}
48
49 4
		$decoded_signing_key = base64_decode( $signing_key );
50 4
51 4
		if ( false === $decoded_signing_key ) {
52 4
			return null;
53
		}
54
55 4
		$combined = self::get_signature_fields_combined( $fields );
56
57
		$signature = hash_hmac(
58
			'sha512',
59
			$combined,
60
			$decoded_signing_key
61
		);
62
63
		return $signature;
64
	}
65 3
66 3
	/**
67
	 * Validate signature.
68
	 *
69
	 * @param string $signature_a Signature A.
70
	 * @param string $signature_b Signature B.
71 3
	 * @return bool True if valid, false otherwise.
72
	 */
73
	public static function validate_signature( $signature_a, $signature_b ) {
74
		if ( empty( $signature_a ) || empty( $signature_b ) ) {
75
			// Empty signature string or null from calculation.
76
			return false;
77
		}
78
79
		return ( 0 === strcasecmp( $signature_a, $signature_b ) );
80
	}
81
}
82