PHP实现3DES加解密

CBC模式一定要指定IV加密向量
ECB模式不需要指定IV加密向量

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
class TripleDes {
/**
* @var string
*/
var $key = '';

/**
* @var string
*/
var $iv = '';

/**
* Des3 constructor.
* @param string|null $key
* @param string|null $iv
*/
public function __construct(string $key=null, string $iv=null)
{
if (!$key && strlen($key) != 24) {
throw new \Exception("3DES_KEY长度错误,长度为24");
}
if (!$iv && strlen($iv) != 8) {
throw new \Exception("3DES_IV长度错误,长度为8");
}
$this->key = $key;
$this->iv = $iv;
}

public function encrypt($input, $key='', $iv='') {
$this->key = $key ? $key : $this->key;
$this->iv = $iv ? $iv : $this->iv;
//return base64_encode(openssl_encrypt($input, "des-ede3-cbc", $this->key, OPENSSL_RAW_DATA, $this->iv));
return base64_encode(openssl_encrypt($input, "des-ede3", $this->key, OPENSSL_RAW_DATA));
}

public function decrypt($encrypted, $key='', $iv='') {
$this->key = $key ? $key : $this->key;
$this->iv = $iv ? $iv : $this->iv;
//return openssl_decrypt(base64_decode($encrypted), 'des-ede3-cbc', $this->key, OPENSSL_RAW_DATA, $this->iv);
return openssl_decrypt(base64_decode($encrypted), 'des-ede3', $this->key, OPENSSL_RAW_DATA);
}
}

注意:(1)3DES密钥的长度必须是8的倍数,可取24位或32位;(2)加密结果的byte数组转换为字符串,一般采用两种方式:Base64处理或十六进制处理。

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :