Passed
Push — master ( 99a753...df0863 )
by Remco
19:34 queued 09:07
created

Security   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Test Coverage

Coverage 64%

Importance

Changes 0
Metric Value
eloc 23
dl 0
loc 67
ccs 16
cts 25
cp 0.64
rs 10
c 0
b 0
f 0
wmc 7

3 Methods

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