- 这里使用
openssl_encrypt
函数,针对PHP7.1以上版本,其中3DES-ECB被包含于DES-EDE3 - 密钥和密文都是十六进制,返回的结果也是十六进制
- 本文参考了博客
https://blog.csdn.net/longke173/article/details/83381104
,在源博客进行修改,增加对密文进行ZEROPADDING(即不是8的倍数,补0到8的倍数),感谢博主提供此博文 - 下面是代码
<?php
class Crypt3DesEcb
{
public static function create()
{
return new self();
}
protected function fromDigit($ch)
{
if (ord($ch) >= ord('0') && ord($ch) <= ord('9')) {
return ord($ch) - ord('0');
}
if (ord($ch) >= ord('A') && ord($ch) <= ord('F')) {
return ord($ch) - ord('A') + 10;
}
if (ord($ch) >= ord('a') && ord($ch) <= ord('f')) {
return ord($ch) - ord('a') + 10;
}
ErrorHandler::throwMessageByErrorCode(ErrorCode::INVALID_HEX_DIGIT);
}
protected function hexStringToBytes($hexString)
{
$len = strlen($hexString);
$buf = [];
$i = 0;
$j = 0;
if (($len % 2) == 1) {
$buf[$j++] = chr($this->fromDigit($hexString[$i++]));
}
while ($i < $len) {
$buf[$j++] = chr(($this->fromDigit($hexString[$i++]) << 4) | $this->fromDigit($hexString[$i++]));
}
return implode($buf);
}
protected function createKeyBytes($key)
{
$temp = $this->hexStringToBytes($key);
$dest = $temp;
if (strlen($temp) < 24) {
$dest = substr($temp, 0, strlen($temp));
$dest .= substr($temp, 0, 24 - strlen($temp));
}
return $dest;
}
protected function convertByteToHexString($bytes)
{
$result = '';
for ($i = 0; $i < strlen($bytes); $i++) {
$temp = ord($bytes[$i]) & 0xff;
$tempHex = dechex($temp);
if (strlen($tempHex) < 2) {
$result .= '0' . $tempHex;
} else {
$result .= $tempHex;
}
}
return strtoupper($result);
}
protected function zeroPadding($hexString)
{
$len = strlen($hexString);
if ($len % 16 != 0) {
$hexString = str_pad($hexString, $len + 16 - $len % 16, 0);
}
return $hexString;
}
public function encrypt($key, $hexString)
{
$result = openssl_encrypt(
$this->hexStringToBytes($this->zeroPadding($hexString)),
'DES-EDE3',
$this->createKeyBytes($key),
OPENSSL_NO_PADDING,
''
);
return $this->convertByteToHexString($result);
}
public function decrypt($key, $hexString)
{
$result = openssl_decrypt(
$this->hexStringToBytes($this->zeroPadding($hexString)),
'DES-EDE3',
$this->createKeyBytes($key),
OPENSSL_NO_PADDING,
'');
return $this->convertByteToHexString($result);
}
}