PHP对称加密类
<?php
/**
* Created by PhpStorm.
* User: zongbinghuang
* Date: 2017/7/31
* Time: 15:13
*/ namespace app\common; use Exception; class BizEncrypt
{
const IV_SIZE = 16;
const CIPHER = 'AES-256-CBC'; private $key;#length:32 public function __construct($key)
{
$key = (string)$key; if (static::supported($key, self::CIPHER)) {
$this->key = $key;
} else {
throw new Exception('The only supported ciphers are AES-256-CBC with the correct key lengths.');
}
} public function encrypt($value)
{
$iv = self::random_bytes(self::IV_SIZE); $value = openssl_encrypt(serialize($value), self::CIPHER, $this->key, 0, $iv); if ($value === false) {
throw new \Exception('Could not encrypt the data.');
} $iv = base64_encode($iv);
$mac = hash_hmac('sha256', $iv . $value, $this->key);
$json = json_encode(compact('iv', 'value', 'mac')); if (!is_string($json)) {
throw new Exception('Could not encrypt the data.');
} return base64_encode($json);
} public function decrypt($payload)
{
$payload = $this->getJsonPayload($payload); $iv = base64_decode($payload['iv']); $decrypted = openssl_decrypt($payload['value'], self::CIPHER, $this->key, 0, $iv); if ($decrypted === false) {
throw new Exception('Could not decrypt the data.');
} return unserialize($decrypted);
} private static function supported($key, $cipher)
{
$length = mb_strlen($key, '8bit'); return ($cipher === 'AES-256-CBC' && $length === 32);
} private function getJsonPayload($payload)
{
$payload = json_decode(base64_decode($payload), true); if (!$payload || $this->invalidPayload($payload)) {
throw new Exception('The payload is invalid.');
} return $payload;
} private function invalidPayload($data)
{
return !is_array($data) || !isset($data['iv']) || !isset($data['value']) || !isset($data['mac']);
} private static function random_bytes($bytes)
{
try {
$bytes = self::RandomCompareInteger($bytes);
} catch (Exception $ex) {
throw new Exception('random_bytes(): $bytes must be an integer');
} if ($bytes < 1) {
throw new Exception('Length must be greater than 0');
} $secure = true;
$buf = openssl_random_pseudo_bytes($bytes, $secure);
if ($buf !== false && $secure && mb_strlen($buf, '8bit') === $bytes) {
return $buf;
} throw new Exception('Could not gather sufficient random data');
} private static function RandomCompareInteger($number, $fail_open = false)
{
if (is_numeric($number)) {
$number += 0;
} if (is_float($number) && $number > ~PHP_INT_MAX && $number < PHP_INT_MAX) {
$number = (int)$number;
} if (is_int($number) || $fail_open) {
return $number;
} throw new Exception('Expected an integer.');
}
}
PHP对称加密类的更多相关文章
- Java常用的加密解密类(对称加密类)
Java常用的加密解密类 原文转载至:http://blog.csdn.net/wyc_cs/article/details/8793198 原创 2013年04月12日 14:33:35 1704 ...
- C#加密类
var es= EncryptSugar.GetInstance(); string word = "abc"; var wordEncrypt = es.Encrypto(wor ...
- .net 对称加密DESCryptoServiceProvider
1.生成密钥以加密和解密数据 DESCryptoServiceProvider 基于一种对称加密算法.对称加密需要密钥和初始化矢量 (IV) 来加密数据.要解密该数据,您必须拥有此同一密钥和 IV.您 ...
- DotNet加密方式解析--对称加密
离过年又近了一天,回家已是近在咫尺,有人欢喜有人愁,因为过几天就得经历每年一度的装逼大戏,亲戚朋友加同学的各方显摆,所以得靠一剂年终奖来装饰一个安稳的年,在这里我想起了一个题目“论装逼的技术性和重要性 ...
- AES对称加密解密类
import java.io.UnsupportedEncodingException; import javax.crypto.Cipher; import javax.crypto.spec.Se ...
- Asp.Net 常用工具类之加密——对称加密DES算法(2)
又到周末,下午博客园看了两篇文章,关于老跳和老赵的程序员生涯,不禁感叹漫漫程序路,何去何从兮! 转眼毕业的第三个年头,去过苏州,跑过上海,从一开始的凌云壮志,去年背起行囊默默回到了长沙准备买房,也想有 ...
- C#不对称加密
对称加密的缺点是双方使用相同的密钥和IV进行加密.解密.由于接收方必须知道密钥和IV才能解密数据,因此发送方需要先将密钥和IV传递给接收方.这就 有一个问题,如果攻击者截获了密钥和IV,也就等于知道了 ...
- 介绍对称加密的另一个算法——PBE
除了DES,我们还知道有DESede(TripleDES,就是3DES).AES.Blowfish.RC2.RC4(ARCFOUR)等多种对称加密方式,其实现方式大同小异,这里介绍对称加密的另一个算法 ...
- 对称加密DES和TripleDES
一. 对称加密 对称加密,是一种比较传统的加密方式,其加密运算.解密运算使用的是同样的密钥,信息的发送者和信息的接收者在进行信息的传输与处理时,必须共同持有该密码(称为对称密码).因此,通信双方都必 ...
随机推荐
- 使用Collectors.toMap遇到NullPointerException
这个坑也是踩过好几次了,记录一笔. 当试图使用Collectors.toMap将一个stream收集为Map的时候,若构造map的valueMapper返回null时,则会报NullPointerEx ...
- La 4670 AC自动机(模版)
#include<iostream> #include<cstring> #include<queue> #include<cstdio> #inclu ...
- 【BZOJ2286】消耗战(虚树,DFS序,树形DP)
题意:一棵N个点的树上有若干个关键点,每条边有一个边权,现在要将这些关键点到1的路径全部切断,切断一条边的代价就是边权. 共有M组询问,每组询问有k[i]个关键点,对于每组询问求出完成任务的最小代价. ...
- Object,String,StringBuffer,StringBuilder,System,Runtime,Date,Math介绍及用法(API)
1 Object对象 面向对象的核心思想:“找合适的对象,做适合的事情”. 合适的对象: 自己描述类,自己创建对象. sun已经描述了好多常用的类,可以使用这些类创建对象. API(App ...
- linux信号-------初涉
一.信号的本质 软中断信号(signal,又简称为信号)用来通知进程发生了异步事件.在软件层次上是对中断机制的一种模拟,在原理上,一个进程收到一个信号与处理器收到一个中断请求可以说是一样的.信号是进程 ...
- LeetCode OJ——Longest Valid Parentheses
http://oj.leetcode.com/problems/longest-valid-parentheses/ 最大括号匹配长度,括号是可以嵌套的 #include <string> ...
- AC日记——[USACO15DEC]最大流Max Flow 洛谷 P3128
题目描述 Farmer John has installed a new system of pipes to transport milk between the stalls in his b ...
- (1)sqlite基础
一.安装sqlite 下载页面:http://www.sqlite.org/download.html 1.下载 sqlite-tools-win32-*.zip 和 sqlite-dll-win32 ...
- FastDFS 使用经验分享
原文:http://www.ttlsa.com/fastdfs/fastdfs-experience-sharing/ 应用背景 文件被上传到FastDFS后Storage服务端将返回的文件索引(FI ...
- TClientDataSet的 fastscript封装
TClientDataSet的 fastscript封装 // 陈新光 2017-2-10// TClientDataSet's fastscript unit fs_ClientDataSet; i ...