|
1
|
|
|
<?php |
|
2
|
|
|
/* |
|
3
|
|
|
* This file is part of the DUKPT package. |
|
4
|
|
|
* |
|
5
|
|
|
* Copyright (c) 2016-2017 Tonic Health <[email protected]> |
|
6
|
|
|
* |
|
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
8
|
|
|
* file that was distributed with this source code. |
|
9
|
|
|
*/ |
|
10
|
|
|
|
|
11
|
|
|
namespace TonicForHealth\DUKPT\Key; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* Class KeySerialNumber |
|
15
|
|
|
* |
|
16
|
|
|
* @author Vitalii Ekert <[email protected]> |
|
17
|
|
|
*/ |
|
18
|
|
|
class KeySerialNumber extends AbstractKey |
|
19
|
|
|
{ |
|
20
|
|
|
const KEY_SIZE_BYTES = 10; |
|
21
|
|
|
const KEY_COUNTER_BYTES = 3; |
|
22
|
|
|
const KEY_INITIAL_MASK = 'FFFFFFFFFFFFFFE00000'; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* Returns the Initial Key Serial Number as a binary data string |
|
26
|
|
|
* |
|
27
|
|
|
* @return string |
|
28
|
|
|
*/ |
|
29
|
15 |
|
public function getInitialKey() |
|
30
|
|
|
{ |
|
31
|
15 |
|
return $this->toBinary() & hex2bin(self::KEY_INITIAL_MASK); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* Returns a value for the Encryption Counter as a binary data string |
|
36
|
|
|
* |
|
37
|
|
|
* @return string |
|
38
|
|
|
*/ |
|
39
|
14 |
|
public function getEncryptionCounter() |
|
40
|
|
|
{ |
|
41
|
14 |
|
return substr($this->toBinary() & ~hex2bin(self::KEY_INITIAL_MASK), -self::KEY_COUNTER_BYTES); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* {@inheritdoc} |
|
46
|
|
|
*/ |
|
47
|
22 |
|
protected function validateKey($binKey) |
|
48
|
|
|
{ |
|
49
|
22 |
|
$keySize = strlen($binKey); |
|
50
|
|
|
|
|
51
|
22 |
|
if (self::KEY_COUNTER_BYTES > $keySize || self::KEY_SIZE_BYTES < $keySize) { |
|
52
|
2 |
|
throw new \InvalidArgumentException( |
|
53
|
2 |
|
sprintf( |
|
54
|
2 |
|
'Invalid KSN size (expected from %d to %d bytes, got %d).', |
|
55
|
2 |
|
self::KEY_COUNTER_BYTES, |
|
56
|
2 |
|
self::KEY_SIZE_BYTES, |
|
57
|
2 |
|
$keySize |
|
58
|
|
|
) |
|
59
|
|
|
); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
20 |
|
return $this->padKey($binKey); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* @param string $binKey |
|
67
|
|
|
* |
|
68
|
|
|
* @return string |
|
69
|
|
|
*/ |
|
70
|
20 |
|
protected function padKey($binKey) |
|
71
|
|
|
{ |
|
72
|
20 |
|
if (self::KEY_SIZE_BYTES > strlen($binKey)) { |
|
73
|
1 |
|
$binKey = str_pad($binKey, self::KEY_SIZE_BYTES, hex2bin('FF'), STR_PAD_LEFT); |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
20 |
|
return $binKey; |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|