|
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
|
|
|
use TonicForHealth\DUKPT\Helper\Encryption\TripleDESEncryptionHelper; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* Class InitialPinEncryptionKeyFactory |
|
17
|
|
|
* |
|
18
|
|
|
* @author Vitalii Ekert <[email protected]> |
|
19
|
|
|
*/ |
|
20
|
|
|
class InitialPinEncryptionKeyFactory implements KeyFactoryInterface |
|
21
|
|
|
{ |
|
22
|
|
|
const ENCRYPTION_INIT_KSN_BYTES = 8; |
|
23
|
|
|
const ENCRYPTION_LOWER_KEY_MASK = 'C0C0C0C000000000C0C0C0C000000000'; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @var TripleDESEncryptionHelper |
|
27
|
|
|
*/ |
|
28
|
|
|
protected $encryptionHelper; |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* InitialPinEncryptionKeyFactory constructor. |
|
32
|
|
|
* |
|
33
|
|
|
* @param TripleDESEncryptionHelper $encryptionHelper |
|
34
|
|
|
*/ |
|
35
|
16 |
|
public function __construct(TripleDESEncryptionHelper $encryptionHelper) |
|
36
|
|
|
{ |
|
37
|
16 |
|
$this->encryptionHelper = $encryptionHelper; |
|
38
|
16 |
|
} |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* {@inheritdoc} |
|
42
|
|
|
* |
|
43
|
|
|
* @return InitialPinEncryptionKey |
|
44
|
|
|
*/ |
|
45
|
13 |
|
public function createFromHexadecimal($hexKey) |
|
46
|
|
|
{ |
|
47
|
13 |
|
return new InitialPinEncryptionKey(hex2bin($hexKey)); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* Returns a key from BDK and KSN |
|
52
|
|
|
* |
|
53
|
|
|
* @param BaseDerivationKey $bdk |
|
54
|
|
|
* @param KeySerialNumber $ksn |
|
55
|
|
|
* |
|
56
|
|
|
* @throws \InvalidArgumentException If the provided key has a wrong size |
|
57
|
|
|
* |
|
58
|
|
|
* @return InitialPinEncryptionKey |
|
59
|
|
|
*/ |
|
60
|
2 |
|
public function create(BaseDerivationKey $bdk, KeySerialNumber $ksn) |
|
61
|
|
|
{ |
|
62
|
2 |
|
$binBDK = $bdk->toBinary(); |
|
63
|
2 |
|
$binInitKSN = $ksn->getInitialKey(); |
|
64
|
2 |
|
$binInitKSNUpperBytes = substr($binInitKSN, 0, self::ENCRYPTION_INIT_KSN_BYTES); |
|
65
|
|
|
|
|
66
|
2 |
|
$binUpperKey = $binBDK; |
|
67
|
2 |
|
$binLowerKey = $binBDK ^ hex2bin(self::ENCRYPTION_LOWER_KEY_MASK); |
|
68
|
|
|
|
|
69
|
2 |
|
$binUpperBytes = $this->encryptionHelper->encrypt($binUpperKey, $binInitKSNUpperBytes); |
|
70
|
2 |
|
$binLowerBytes = $this->encryptionHelper->encrypt($binLowerKey, $binInitKSNUpperBytes); |
|
71
|
|
|
|
|
72
|
2 |
|
$binKey = $binUpperBytes.$binLowerBytes; |
|
73
|
|
|
|
|
74
|
2 |
|
return new InitialPinEncryptionKey($binKey); |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|