1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ByJG\Crypto; |
4
|
|
|
|
5
|
|
|
|
6
|
|
|
abstract class TripleDes implements CryptoInterface |
7
|
|
|
{ |
8
|
|
|
|
9
|
|
|
abstract public function getKeys(); |
10
|
|
|
|
11
|
|
|
public function getKeyPart($keyNumber, $part) |
12
|
|
|
{ |
13
|
|
|
$keyPart = $this->getKeys(); |
14
|
|
|
$blockSize = mcrypt_get_block_size(MCRYPT_3DES, MCRYPT_MODE_CBC) * 2; |
15
|
|
|
|
16
|
|
View Code Duplication |
if ($part == 1) { |
|
|
|
|
17
|
|
|
return substr(hex2bin($keyPart[$keyNumber]), 0, $blockSize); |
18
|
|
|
} else { |
19
|
|
|
return substr(hex2bin($keyPart[$keyNumber]), -$blockSize); |
20
|
|
|
} |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public function encrypt($plainText) |
24
|
|
|
{ |
25
|
|
|
$maxPossibleKeys = count($this->getKeys()) - 1; |
26
|
|
|
$blockSize = mcrypt_get_block_size(MCRYPT_3DES, MCRYPT_MODE_CBC); |
27
|
|
|
|
28
|
|
|
$bitA = rand(0, $maxPossibleKeys); |
29
|
|
|
$bitB = rand(0, $maxPossibleKeys); |
30
|
|
|
|
31
|
|
|
$key = $this->getKeyPart($bitA, 1); |
32
|
|
|
$iv = substr($this->getKeyPart($bitB, 2), 0, $blockSize); |
33
|
|
|
|
34
|
|
|
$padded = $this->pkcs5Pad($plainText, $blockSize); |
35
|
|
|
|
36
|
|
|
$encText = mcrypt_encrypt(MCRYPT_3DES, $key, $padded, MCRYPT_MODE_CBC, $iv); |
37
|
|
|
|
38
|
|
|
return base64_encode(bin2hex(chr($bitA)) . bin2hex(chr($bitB)) . $encText); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public function decrypt($encryptText) { |
42
|
|
|
|
43
|
|
|
$cipherText = base64_decode($encryptText); |
44
|
|
|
|
45
|
|
|
$bitA = ord(hex2bin(substr($cipherText, 0, 2))); |
46
|
|
|
$bitB = ord(hex2bin(substr($cipherText, 2, 2))); |
47
|
|
|
|
48
|
|
|
$key = $this->getKeyPart($bitA, 1); |
49
|
|
|
$iv = substr($this->getKeyPart($bitB, 2), 0, mcrypt_get_block_size(MCRYPT_3DES, MCRYPT_MODE_CBC)); |
50
|
|
|
|
51
|
|
|
$res = mcrypt_decrypt(MCRYPT_3DES, $key, substr($cipherText, 4), MCRYPT_MODE_CBC, $iv); |
52
|
|
|
|
53
|
|
|
return $this->pkcs5Unpad($res); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
|
57
|
|
|
protected function pkcs5Pad ($text, $blocksize) |
58
|
|
|
{ |
59
|
|
|
$pad = $blocksize - (strlen($text) % $blocksize); |
60
|
|
|
return $text . str_repeat(chr($pad), $pad); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
protected function pkcs5Unpad($text) |
64
|
|
|
{ |
65
|
|
|
$pad = ord($text{strlen($text)-1}); |
66
|
|
|
if ($pad > strlen($text)) { |
67
|
|
|
return false; |
68
|
|
|
} |
69
|
|
|
if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) { |
70
|
|
|
return false; |
71
|
|
|
} |
72
|
|
|
return substr($text, 0, -1 * $pad); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
} |
76
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.