PHP7 OpenSSL DES-EDE-CBC加解密

本文阅读 1 分钟
首页 PHP笔记 正文

1.条件约束
之前PHP5上常使用的mcrypt库在PHP7.1+上已经被移除,故我们采用openssl对数据进行加解密。
加密方式采用DES-EDE-CBC方式。
密钥填充方式为:采用24位密钥,先将key进行MD5校验取值,得出16位字串,再取key MD5校验值前8位追加到先前的取值后面。由此组装出24位的密钥。

  1. 代码分享

    1. class DesEdeCbc {
    2. private $cipher, $key, $iv;
    3. /**
    4. * DesEdeCbc constructor.
    5. * @param $cipher
    6. * @param $key
    7. * @param $iv
    8. */
    9. public function __construct($cipher, $key, $iv) {
    10. $this->cipher = $cipher;
    11. $this->key= $this->getFormatKey($key);
    12. $this->iv = $iv;
    13. }
    14. /**
    15. * @func 加密
    16. * @param $msg
    17. * @return string
    18. */
    19. public function encrypt($msg) {
    20. $des = @openssl_encrypt($msg, $this->cipher, $this->key, OPENSSL_RAW_DATA, $this->iv);
    21. return base64_encode($des);
    22. }
    23. /**
    24. * @func 解密
    25. * @param $msg
    26. * @return string
    27. */
    28. public function decrypt($msg) {
    29. return @openssl_decrypt(base64_decode($msg), $this->cipher, $this->key, OPENSSL_RAW_DATA, $this->iv);
    30. }
    31. /**
    32. * @func 生成24位长度的key
    33. * @param $skey
    34. * @return bool|string
    35. */
    36. private function getFormatKey($skey) {
    37. $md5Value= md5($skey);
    38. $md5ValueLen = strlen($md5Value);
    39. $key = $md5Value . substr($md5Value, 0, $md5ValueLen / 2);
    40. return hex2bin($key);
    41. }
    42. }
    43. $cipher = 'DES-EDE-CBC';
    44. $msg = 'HelloWorld';
    45. $key = '12345678';
    46. $iv = "\x00\x00\x00\x00\x00\x00\x00\x00";
    47. $des = new DesEdeCbc($cipher, $key, $iv);
    48. // 加密
    49. $msg = $des->encrypt($msg);
    50. echo '加密后: ' . $msg . PHP_EOL;
    51. // 解密
    52. $src = $des->decrypt($msg);
    53. echo '解密后: ' . $src . PHP_EOL;
  2. 一点说明
    可以根据实际情况调整加密方式、key的填充方式、及iv向量来满足不同的需求。
解压密码: detechn或detechn.com

免责声明

本站所有资源出自互联网收集整理,本站不参与制作,如果侵犯了您的合法权益,请联系本站我们会及时删除。

本站发布资源来源于互联网,可能存在水印或者引流等信息,请用户自行鉴别,做一个有主见和判断力的用户。

本站资源仅供研究、学习交流之用,若使用商业用途,请购买正版授权,否则产生的一切后果将由下载用户自行承担。

php7.2中mcrypt转openssl的方法详解
« 上一篇 01-13
《进化式运营:从互联网菜鸟到绝顶高手》 mobi
下一篇 » 01-19

发表评论