forked from kevinsandow/PBEWithMD5AndDES
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PbeWithMd5AndDes.php
79 lines (64 loc) · 2 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
<?php
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 _getCharRandonSalt($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::_getCharRandonSalt();
$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 informazionr 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));
}
}