php7 des,PHP7实现OpenSSL DES

编程入门 行业动态 更新时间:2024-10-06 10:35:56

php7 <a href=https://www.elefans.com/category/jswz/34/1770421.html style=des,PHP7实现OpenSSL DES"/>

php7 des,PHP7实现OpenSSL DES

PHP7实现OpenSSL DES-EDE-CBC加密和解密

发布时间:2020-05-22 18:16:33

来源:亿速云

阅读:213

作者:鸽子

1. 条件约束

之前PHP5上常使用的mcrypt库在PHP7.1+上已经被移除,故我们采用openssl对数据进行加解密。

加密方式采用DES-EDE-CBC方式。

密钥填充方式为:采用24位密钥,先将key进行MD5校验取值,得出16位字串,再取key MD5校验值前8位追加到先前的取值后面。由此组装出24位的密钥。

2. 代码分享<?php

class DesEdeCbc {

private $cipher, $key, $iv;

/**

* DesEdeCbc constructor.

* @param $cipher

* @param $key

* @param $iv

*/

public function __construct($cipher, $key, $iv) {

$this->cipher = $cipher;

$this->key= $this->getFormatKey($key);

$this->iv = $iv;

}

/**

* @func 加密

* @param $msg

* @return string

*/

public function encrypt($msg) {

$des = @openssl_encrypt($msg, $this->cipher, $this->key, OPENSSL_RAW_DATA, $this->iv);

return base64_encode($des);

}

/**

* @func 解密

* @param $msg

* @return string

*/

public function decrypt($msg) {

return @openssl_decrypt(base64_decode($msg), $this->cipher, $this->key, OPENSSL_RAW_DATA, $this->iv);

}

/**

* @func 生成24位长度的key

* @param $skey

* @return bool|string

*/

private function getFormatKey($skey) {

$md5Value= md5($skey);

$md5ValueLen = strlen($md5Value);

$key = $md5Value . substr($md5Value, 0, $md5ValueLen / 2);

return hex2bin($key);

}

}

$cipher = 'DES-EDE-CBC';

$msg = 'HelloWorld';

$key = '12345678';

$iv = "\x00\x00\x00\x00\x00\x00\x00\x00";

$des = new DesEdeCbc($cipher, $key, $iv);

// 加密

$msg = $des->encrypt($msg);

echo '加密后: ' . $msg . PHP_EOL;

// 解密

$src = $des->decrypt($msg);

echo '解密后: ' . $src . PHP_EOL;

3. 一点说明

可以根据实际情况调整加密方式、key的填充方式、及iv向量来满足不同的需求。

更多推荐

php7 des,PHP7实现OpenSSL DES

本文发布于:2024-02-28 12:08:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1769490.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:des   DES   OpenSSL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!