-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCryptoJSDES.php
63 lines (49 loc) · 1.73 KB
/
CryptoJSDES.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
<?php
class CryptoJSDES {
/**
* @param $data
* @param $passphrase
* @param null $salt ONLY FOR TESTING
* @return string encrypted data in base64 OpenSSL format
*/
public static function encrypt($data, $passphrase, $salt = null) {
$salt = $salt ?: openssl_random_pseudo_bytes(8);
list($key, $iv) = self::evpkdf($passphrase, $salt);
$ct = openssl_encrypt($data, 'des-cbc', $key, true, $iv);
return self::encode($ct, $salt);
}
/**
* @param string $base64 encrypted data in base64 OpenSSL format
* @param string $passphrase
* @return string
*/
public static function decrypt($base64, $passphrase) {
list($ct, $salt) = self::decode($base64);
list($key, $iv) = self::evpkdf($passphrase, $salt);
$data = openssl_decrypt($ct, 'des-cbc', $key, true, $iv);
return $data;
}
public static function evpkdf($passphrase, $salt) {
$salted = '';
$dx = '';
while (strlen($salted) < 48) {
$dx = md5($dx . $passphrase . $salt, true);
$salted .= $dx;
}
$key = substr($salted, 0, 8); //AES将length:8改成32
$iv = substr($salted, 8, 8); //AES将offset:8改成32,length:8改成16
return [$key, $iv];
}
public static function decode($base64) {
$data = base64_decode($base64);
if (substr($data, 0, 8) !== "Salted__") {
throw new \InvalidArgumentException();
}
$salt = substr($data, 8, 8);
$ct = substr($data, 16);
return [$ct, $salt];
}
public static function encode($ct, $salt) {
return base64_encode("Salted__" . $salt . $ct);
}
}