1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: zongbinghuang
  5. * Date: 2017/7/31
  6. * Time: 15:13
  7. */
  8.  
  9. namespace app\common;
  10.  
  11. use Exception;
  12.  
  13. class BizEncrypt
  14. {
  15. const IV_SIZE = 16;
  16. const CIPHER = 'AES-256-CBC';
  17.  
  18. private $key;#length:32
  19.  
  20. public function __construct($key)
  21. {
  22. $key = (string)$key;
  23.  
  24. if (static::supported($key, self::CIPHER)) {
  25. $this->key = $key;
  26. } else {
  27. throw new Exception('The only supported ciphers are AES-256-CBC with the correct key lengths.');
  28. }
  29. }
  30.  
  31. public function encrypt($value)
  32. {
  33. $iv = self::random_bytes(self::IV_SIZE);
  34.  
  35. $value = openssl_encrypt(serialize($value), self::CIPHER, $this->key, 0, $iv);
  36.  
  37. if ($value === false) {
  38. throw new \Exception('Could not encrypt the data.');
  39. }
  40.  
  41. $iv = base64_encode($iv);
  42. $mac = hash_hmac('sha256', $iv . $value, $this->key);
  43. $json = json_encode(compact('iv', 'value', 'mac'));
  44.  
  45. if (!is_string($json)) {
  46. throw new Exception('Could not encrypt the data.');
  47. }
  48.  
  49. return base64_encode($json);
  50. }
  51.  
  52. public function decrypt($payload)
  53. {
  54. $payload = $this->getJsonPayload($payload);
  55.  
  56. $iv = base64_decode($payload['iv']);
  57.  
  58. $decrypted = openssl_decrypt($payload['value'], self::CIPHER, $this->key, 0, $iv);
  59.  
  60. if ($decrypted === false) {
  61. throw new Exception('Could not decrypt the data.');
  62. }
  63.  
  64. return unserialize($decrypted);
  65. }
  66.  
  67. private static function supported($key, $cipher)
  68. {
  69. $length = mb_strlen($key, '8bit');
  70.  
  71. return ($cipher === 'AES-256-CBC' && $length === 32);
  72. }
  73.  
  74. private function getJsonPayload($payload)
  75. {
  76. $payload = json_decode(base64_decode($payload), true);
  77.  
  78. if (!$payload || $this->invalidPayload($payload)) {
  79. throw new Exception('The payload is invalid.');
  80. }
  81.  
  82. return $payload;
  83. }
  84.  
  85. private function invalidPayload($data)
  86. {
  87. return !is_array($data) || !isset($data['iv']) || !isset($data['value']) || !isset($data['mac']);
  88. }
  89.  
  90. private static function random_bytes($bytes)
  91. {
  92. try {
  93. $bytes = self::RandomCompareInteger($bytes);
  94. } catch (Exception $ex) {
  95. throw new Exception('random_bytes(): $bytes must be an integer');
  96. }
  97.  
  98. if ($bytes < 1) {
  99. throw new Exception('Length must be greater than 0');
  100. }
  101.  
  102. $secure = true;
  103. $buf = openssl_random_pseudo_bytes($bytes, $secure);
  104. if ($buf !== false && $secure && mb_strlen($buf, '8bit') === $bytes) {
  105. return $buf;
  106. }
  107.  
  108. throw new Exception('Could not gather sufficient random data');
  109. }
  110.  
  111. private static function RandomCompareInteger($number, $fail_open = false)
  112. {
  113. if (is_numeric($number)) {
  114. $number += 0;
  115. }
  116.  
  117. if (is_float($number) && $number > ~PHP_INT_MAX && $number < PHP_INT_MAX) {
  118. $number = (int)$number;
  119. }
  120.  
  121. if (is_int($number) || $fail_open) {
  122. return $number;
  123. }
  124.  
  125. throw new Exception('Expected an integer.');
  126. }
  127. }

PHP对称加密类的更多相关文章

  1. Java常用的加密解密类(对称加密类)

    Java常用的加密解密类 原文转载至:http://blog.csdn.net/wyc_cs/article/details/8793198 原创 2013年04月12日 14:33:35 1704 ...

  2. C#加密类

    var es= EncryptSugar.GetInstance(); string word = "abc"; var wordEncrypt = es.Encrypto(wor ...

  3. .net 对称加密DESCryptoServiceProvider

    1.生成密钥以加密和解密数据 DESCryptoServiceProvider 基于一种对称加密算法.对称加密需要密钥和初始化矢量 (IV) 来加密数据.要解密该数据,您必须拥有此同一密钥和 IV.您 ...

  4. DotNet加密方式解析--对称加密

    离过年又近了一天,回家已是近在咫尺,有人欢喜有人愁,因为过几天就得经历每年一度的装逼大戏,亲戚朋友加同学的各方显摆,所以得靠一剂年终奖来装饰一个安稳的年,在这里我想起了一个题目“论装逼的技术性和重要性 ...

  5. AES对称加密解密类

    import java.io.UnsupportedEncodingException; import javax.crypto.Cipher; import javax.crypto.spec.Se ...

  6. Asp.Net 常用工具类之加密——对称加密DES算法(2)

    又到周末,下午博客园看了两篇文章,关于老跳和老赵的程序员生涯,不禁感叹漫漫程序路,何去何从兮! 转眼毕业的第三个年头,去过苏州,跑过上海,从一开始的凌云壮志,去年背起行囊默默回到了长沙准备买房,也想有 ...

  7. C#不对称加密

    对称加密的缺点是双方使用相同的密钥和IV进行加密.解密.由于接收方必须知道密钥和IV才能解密数据,因此发送方需要先将密钥和IV传递给接收方.这就 有一个问题,如果攻击者截获了密钥和IV,也就等于知道了 ...

  8. 介绍对称加密的另一个算法——PBE

    除了DES,我们还知道有DESede(TripleDES,就是3DES).AES.Blowfish.RC2.RC4(ARCFOUR)等多种对称加密方式,其实现方式大同小异,这里介绍对称加密的另一个算法 ...

  9. 对称加密DES和TripleDES

    一.  对称加密 对称加密,是一种比较传统的加密方式,其加密运算.解密运算使用的是同样的密钥,信息的发送者和信息的接收者在进行信息的传输与处理时,必须共同持有该密码(称为对称密码).因此,通信双方都必 ...

随机推荐

  1. java面试题之谈谈你对java的理解

    平台无关性:一处编译到处运行 GC:不用像c++那样手动释放堆内容 语言特性:泛型.反射.lamda表达式 面向对象:封装.继承.多态 类库:集合.并发库.网络库.IO库 异常处理

  2. [转] Makefile 基础 (8) —— Makefile 隐含规则

    该篇文章为转载,是对原作者系列文章的总汇加上标注. 支持原创,请移步陈浩大神博客:(最原始版本) http://blog.csdn.net/haoel/article/details/2886 我转自 ...

  3. git统计日期之间的代码改动行数

    git log --pretty=tformat: --since ==2016-10-25 --until=2016-10-27   --numstat | awk '{ add += $1 ; s ...

  4. SqlLite 安装与使用

    一.安装文件 官方下载地址: http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki 选择要下载的类库文件:sqli ...

  5. 【CF56E】Domino Principle(线性扫描,伪DP)

    每块多米诺骨牌所在的位置设为x,每块多米诺骨牌高度为h.如果将x位置上的多米诺骨牌向右翻到,它就可以影响[x+1, x+h-1]范围内的所有多米诺骨牌,让他们也翻到,同时这些被翻到的多米诺骨牌还能影响 ...

  6. elementui table 分页 和 tabel 前加序列号

    记录下来备忘 结构如下 Report.vue <template> <div> <home-header></home-header> <div ...

  7. css选择器浅谈

    css选择器有很多,种类的话总结起来有5种.即: id选择器,class选择器,elements选择器,级联选择器,相邻选择器. 前三个没什么好说的,分别是id,class和标签的选择,注意选中对象的 ...

  8. 百度图表echars插件使用案例

    <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding= ...

  9. PXC集群资料整理

    1.mysql集群方案对比 方案1  NDBCluster  参考:https://www.cnblogs.com/kevingrace/p/5685371.html?utm_source=itdad ...

  10. poj 1970(搜索)

    The Game Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 6247   Accepted: 1601 Descript ...