-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathPBEWithMD5AndDES.php
96 lines (80 loc) · 2.42 KB
/
PBEWithMD5AndDES.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?php
namespace PBEWithMD5AndDES;
class PBEWithMD5AndDES
{
//"Magic" keyword used by OpenSSL to put at the beginning of the encrypted
// bytes.
private static $MAGIC_SALTED_BYTES = "Salted__";
private static function getCharRandomSalt($length = 16)
{
$salt = '';
for ($n = 0; $n < $length; $n++) {
$salt .= dechex(mt_rand(0, 0xF));
}
return $salt;
}
public static function encrypt(
$data,
$keyString,
$salt = null,
$iterationsMD5 = 1,
$segments = 1
) {
$useRandomSalt = false;
if ($salt === null) {
$salt = PBEWithMD5AndDES::getCharRandomSalt();
$useRandomSalt = true;
/**
* Number of iterations -
* needs to be set to 1 for our roundtrip to work.
*/
$iterationsMD5 = 1;
}
$pkcsKeyGenerator = new PKCSKeyGenerator(
$keyString,
$salt,
$iterationsMD5,
$segments
);
$encryptor = new DESEncryptor(
$pkcsKeyGenerator->getKey(),
$pkcsKeyGenerator->getIv()
);
$crypt = $encryptor->transformFinalBlock($data);
if ($useRandomSalt) {
// add the magic keyword, salt information and encrypted byte
$crypt = PBEWithMD5AndDES::$MAGIC_SALTED_BYTES
. pack("H*", $salt)
. $crypt;
}
// base64 encode so we can send it around as a string
return base64_encode($crypt);
}
public static function decrypt(
$data,
$keyString,
$salt = null,
$iterationsMD5 = 1,
$segments = 1
) {
if ($salt === null) {
// Get the salt information from the input
$salt = bin2hex(substr(base64_decode($data), 8, 8));
$data = base64_encode(substr(base64_decode($data), 16));
//Number of iterations - needs to be set to 1 for our roundtrip to work
$iterationsMD5 = 1;
}
$pkcsKeyGenerator = new PKCSKeyGenerator(
$keyString,
$salt,
$iterationsMD5,
$segments
);
$encryptor = new DESEncryptor(
$pkcsKeyGenerator->getKey(),
$pkcsKeyGenerator->getIv(),
false
);
return $encryptor->transformFinalBlock(base64_decode($data));
}
}