Failed Conditions
Push — master ( dcd2a1...e6b844 )
by Reüel
13:36 queued 05:05
created

Security   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Test Coverage

Coverage 60.87%

Importance

Changes 8
Bugs 0 Features 0
Metric Value
eloc 21
c 8
b 0
f 0
dl 0
loc 66
ccs 14
cts 23
cp 0.6087
rs 10
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A get_signature_fields_combined() 0 2 1
A get_signature() 0 29 3
A validate_signature() 0 9 3
1
<?php
2
/**
3
 * Security
4
 *
5
 * @author    Pronamic <[email protected]>
6
 * @copyright 2005-2020 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.1.8
18
 * @since   1.0.0
19
 */
20
class Security {
21
	/**
22
	 * Get signature fields combined.
23
	 *
24
	 * @param array<string> $fields Fields.
25
	 * @return string
26
	 */
27 6
	public static function get_signature_fields_combined( $fields ) {
28 6
		return \implode( ',', $fields );
29
	}
30
31
	/**
32
	 * Calculdate signature for specific data.
33
	 *
34
	 * @param Signable $signable    Signable object.
35
	 * @param string   $signing_key Signing Key.
36
	 * @return string
37
	 * @throws \InvalidArgumentException Signing key is invalid.
38
	 */
39 4
	public static function get_signature( Signable $signable, $signing_key ) {
40 4
		if ( empty( $signing_key ) ) {
41
			throw new \InvalidArgumentException(
42
				\sprintf(
43
					'Signing key "%s" is empty.',
44
					$signing_key
45
				)
46
			);
47
		}
48
49
		// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
50 4
		$decoded_signing_key = \base64_decode( $signing_key, true );
51
52 4
		if ( false === $decoded_signing_key ) {
53
			throw new \InvalidArgumentException(
54
				\sprintf(
55
					'Signing key "%s" contains character from outside the base64 alphabet.',
56
					$signing_key
57
				)
58
			);
59
		}
60
61 4
		$fields = $signable->get_signature_fields();
62
63 4
		$combined = self::get_signature_fields_combined( $fields );
64
65 4
		$signature = \hash_hmac( 'sha512', $combined, $decoded_signing_key );
66
67 4
		return $signature;
68
	}
69
70
	/**
71
	 * Validate signature.
72
	 *
73
	 * @param string $signature_a Signature A.
74
	 * @param string $signature_b Signature B.
75
	 * @return bool True if valid, false otherwise.
76
	 */
77 3
	public static function validate_signature( $signature_a, $signature_b ) {
78 3
		if ( empty( $signature_a ) || empty( $signature_b ) ) {
79
			// Empty signature string or null from calculation.
80
			return false;
81
		}
82
83 3
		$result = ( 0 === \strcasecmp( $signature_a, $signature_b ) );
84
85 3
		return $result;
86
	}
87
}
88