-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathDESEncryptor.php
81 lines (72 loc) · 1.89 KB
/
DESEncryptor.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
namespace PBEWithMD5AndDES;
class DESEncryptor
{
protected $key;
protected $iv;
protected $blockSize = 8;
protected $encrypt;
protected $cipher;
/**
* Creates a symmetric Data Encryption Standard (DES) encryptor object
* with the specified key and initialization vector.
*
* @param string $key key
* @param string $iv initialization vettor
* @param bool $encrypt whether we should encrypt or decrypt
*/
public function __construct($key, $iv, $encrypt = true)
{
$this->key = $key;
$this->iv = $iv;
$this->encrypt = $encrypt;
}
/**
* Transforms the specified region of the specified byte array using
* PCKS7 padding.
*
* @param string $text
*
* @return string
*/
public function transformFinalBlock($text)
{
if ($this->encrypt) {
$padding = $this->blockSize - strlen($text) % $this->blockSize;
$text .= str_repeat(pack('C', $padding), $padding);
}
$text = $this->transformBlock($text);
if (!$this->encrypt) {
$aPadding = array_values(unpack('C', substr($text, -1)));
$padding = $aPadding[0];
$text = substr($text, 0, strlen($text) - $padding);
}
return $text;
}
/**
* Transforms the specified region of the specified byte array.
*
* @param string $text
*
* @return string
*/
public function transformBlock($text)
{
if ($this->encrypt) {
return openssl_encrypt(
$text,
'DES-CBC',
$this->key,
OPENSSL_RAW_DATA,
$this->iv
);
}
return openssl_decrypt(
$text,
'DES-CBC',
$this->key,
OPENSSL_RAW_DATA,
$this->iv
);
}
}