|
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\Helper\Encryption; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* Class AbstractEncryptionHelper |
|
15
|
|
|
* |
|
16
|
|
|
* @author Vitalii Ekert <[email protected]> |
|
17
|
|
|
*/ |
|
18
|
|
|
abstract class AbstractEncryptionHelper implements EncryptionHelperInterface |
|
19
|
|
|
{ |
|
20
|
|
|
const BLOCK_SIZE_BYTES = 8; |
|
21
|
|
|
const NULL_CHAR = "\0"; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* {@inheritdoc} |
|
25
|
|
|
*/ |
|
26
|
16 |
|
public function encrypt($key, $data) |
|
27
|
|
|
{ |
|
28
|
16 |
|
return openssl_encrypt($this->getPaddedData($data), $this->getCipherMethod(), $key, $this->getOptions(), $this->getIV()); |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* {@inheritdoc} |
|
33
|
|
|
*/ |
|
34
|
6 |
|
public function decrypt($key, $data) |
|
35
|
|
|
{ |
|
36
|
6 |
|
return rtrim(openssl_decrypt($data, $this->getCipherMethod(), $key, $this->getOptions(), $this->getIV()), self::NULL_CHAR); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* Returns one of the available cipher methods |
|
41
|
|
|
* |
|
42
|
|
|
* @see openssl_get_cipher_methods() |
|
43
|
|
|
* |
|
44
|
|
|
* @return string |
|
45
|
|
|
*/ |
|
46
|
|
|
abstract protected function getCipherMethod(); |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* @param string $data |
|
50
|
|
|
* |
|
51
|
|
|
* @return string |
|
52
|
|
|
*/ |
|
53
|
16 |
|
private function getPaddedData($data) |
|
54
|
|
|
{ |
|
55
|
16 |
|
$length = strlen($data); |
|
56
|
16 |
|
$offset = $length % self::BLOCK_SIZE_BYTES; |
|
57
|
|
|
|
|
58
|
16 |
|
return (0 === $offset) ? $data : str_pad($data, $length + self::BLOCK_SIZE_BYTES - $offset, self::NULL_CHAR); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* @return int |
|
63
|
|
|
*/ |
|
64
|
22 |
|
private function getOptions() |
|
65
|
|
|
{ |
|
66
|
22 |
|
return OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
/** |
|
70
|
|
|
* Returns the IV belonging to a specific cipher/mode combination |
|
71
|
|
|
* |
|
72
|
|
|
* @return string |
|
73
|
|
|
*/ |
|
74
|
22 |
|
private function getIV() |
|
75
|
|
|
{ |
|
76
|
22 |
|
return str_repeat(self::NULL_CHAR, openssl_cipher_iv_length($this->getCipherMethod())); |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|