【笔记】PHP实现DES加解密

前言

PHP实现DES加解密

工具类

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
class DES {
protected $method;
protected $key;
protected $output;
protected $iv;
protected $options;

const OUTPUT_NULL = '';
const OUTPUT_BASE64 = 'base64';
const OUTPUT_HEX = 'hex';

public function __construct($key, $method = 'DES-ECB', $output = '', $iv = '', $options = OPENSSL_RAW_DATA | OPENSSL_NO_PADDING) {
$this->key = $key;
$this->method = $method;
$this->output = $output;
$this->iv = $iv;
$this->options = $options;
}

public function encrypt($str) {
$str = $this->pkcsPadding($str, 8);
$sign = openssl_encrypt($str, $this->method, $this->key, $this->options, $this->iv);
if ($this->output == self::OUTPUT_BASE64) {
$sign = base64_encode($sign);
} else if ($this->output == self::OUTPUT_HEX) {
$sign = bin2hex($sign);
}
return $sign;
}

public function decrypt($encrypted) {
if ($this->output == self::OUTPUT_BASE64) {
$encrypted = base64_decode($encrypted);
} else if ($this->output == self::OUTPUT_HEX) {
$encrypted = hex2bin($encrypted);
}
$sign = @openssl_decrypt($encrypted, $this->method, $this->key, $this->options, $this->iv);
$sign = $this->unPkcsPadding($sign);
return rtrim($sign);
}

private function pkcsPadding($str, $blocksize) {
$pad = $blocksize - (strlen($str) % $blocksize);
return $str . str_repeat(chr($pad), $pad);
}

private function unPkcsPadding($str) {
$pad = ord($str[strlen($str) - 1]);
if ($pad > strlen($str)) {
return false;
}
return substr($str, 0, -1 * $pad);
}
}

DES加密

1
base64_encode(openssl_encrypt($data, 'DES-CBC', $key, OPENSSL_RAW_DATA, $iv));

DES解密

1
openssl_decrypt(base64_decode($data), 'DES-CBC', $key, OPENSSL_RAW_DATA, $iv);

完成