<?php
/**
*open ssl 的使用
*Op_get_random_bytes() 随机生成指定长度的字符
*加密和解密是相反的 公钥加密就要私钥解密(反之亦然)
*Op_encrypt() 加密函数
*Op_decrypt() 解密函数
*Op_base64() 特殊字符和十进制字符的转化
*/
/**===============================================
*$len 要生成的字符长度(如果不指定默认取10个长度)
*$type 0 或者 1
* 0 是直接返回特殊字符
* 1 返回经过转化的二进制字符
*返回值 成功返回字符串 失败返回false
*/
function Op_get_random_bytes($len = 0,$type = 0)
{
$len = $len ? $len : 10;
$type = $type ? $type : 0;
$content = openssl_random_pseudo_bytes($len,$bool);
if($bool)
{
if($type == 1)
{
return Op_base64($content);
}else{
return $content;
}
}else{
return false;
}
}
/**====================================================
*$path 证书文件路径
*$data 加密的数据
*$type 0 公钥解密(默认) 1 私钥解密
*$st 0 不经base64 转化(默认) 1 经base64转化
*返回值 成功返回加密后数据 失败返回false 或者 错误提示
*/
function Op_encrypt($path,$data,$type = 0,$st = 0)
{
//获取证书内容
$key_content = file_get_contents($path);
if($type == 1)
{
$content = openssl_pkey_get_public($key_content);
}else{
$content = openssl_pkey_get_private($key_content);
}
if(!content)
{
return '证书不可用';
}
if($type == 1)
{
$encry_data = openssl_public_encrypt($data);
}else{
$encry_data = openssl_private_encrypt($data);
}
//加密后的内容通常含有特殊字符,需要编码转换下
if($st)
{
return Op_base64($encry_data);
}else{
return $encry_data;
}
}
/**=====================================================
*$path 证书文件路径
*$data 解密的数据
*$type 0 公钥解密(默认) 1 私钥解密
*$st 0 不经base64(默认) 转化 1 经base64转化
*返回值 成功返回解密后数据 失败返回false 或者 错误提示
*/
function Op_decrypt($path,$data,$type = 0,$st = 0)
{
//获取证书内容
$key_content = file_get_contents($path);
if($type == 1)
{
$content = openssl_pkey_get_public($key_content);
}else{
$content = openssl_pkey_get_private($key_content);
}
if(!content)
{
return '证书不可用';
}
if($type == 1)
{
$decry_data = openssl_public_decrypt($data);
}else{
$decry_data = openssl_private_decrypt($data);
}
if($st)
{
return Op_base64($decry_data);
}else{
return $decry_data;
}
}
/**=====================================================
*$str 要转换的字符串
*$type 选择转换的类型(0 1)#0 特殊字符转换为十进制(默认) #1 十进制转换为特殊字符
*返回值 转换过后的字符串
*/
function Op_base64($str,$type = 0)
{
$type = $type ? $type : 0;
if($type == 1)
{
return base64_decode($str);
}else{
return base64_encode($str);
}
}
?>
openssl证书数据加密和解密
最新推荐文章于 2022-11-23 16:05:26 发布