php RAS加密类代码

通过openssl实现的签名、验签、非对称加解密,需要配合x.509证书(如crt和pem)文件使用。

<?php
/**
 * RSA算法类
 * 签名及密文编码:base64字符串/十六进制字符串/二进制字符串流
 * 填充方式: PKCS1Padding(加解密)/NOPadding(解密)
 *
 * Notice:Only accepts a single block. Block size is equal to the RSA key size!
 * 如密钥长度为1024 bit,则加密时数据需小于128字节,加上PKCS1Padding本身的11字节信息,所以明文需小于117字节
 *
 * @author: linvo
 * @version: 1.0.0
 * @date: 2013/1/23
 */
class RSA{ 

    private $pubKey = null;
    private $priKey = null; 

    /**
     * 自定义错误处理
     */
    private function _error($msg){
        die(‘RSA Error:‘ . $msg); //TODO
    } 

    /**
     * 构造函数
     *
     * @param string 公钥文件(验签和加密时传入)
     * @param string 私钥文件(签名和解密时传入)
     */
    public function __construct($public_key_file = ‘‘, $private_key_file = ‘‘){
        if ($public_key_file){
            $this->_getPublicKey($public_key_file);
        }
        if ($private_key_file){
            $this->_getPrivateKey($private_key_file);
        }
    } 

    /**
     * 生成签名
     *
     * @param string 签名材料
     * @param string 签名编码(base64/hex/bin)
     * @return 签名值
     */
    public function sign($data, $code = ‘base64‘){
        $ret = false;
        if (openssl_sign($data, $ret, $this->priKey)){
            $ret = $this->_encode($ret, $code);
        }
        return $ret;
    } 

    /**
     * 验证签名
     *
     * @param string 签名材料
     * @param string 签名值
     * @param string 签名编码(base64/hex/bin)
     * @return bool
     */
    public function verify($data, $sign, $code = ‘base64‘){
        $ret = false;
        $sign = $this->_decode($sign, $code);
        if ($sign !== false) {
            switch (openssl_verify($data, $sign, $this->pubKey)){
                case 1: $ret = true; break;
                case 0:
                case -1:
                default: $ret = false;
            }
        }
        return $ret;
    } 

    /**
     * 加密
     *
     * @param string 明文
     * @param string 密文编码(base64/hex/bin)
     * @param int 填充方式(貌似php有bug,所以目前仅支持OPENSSL_PKCS1_PADDING)
     * @return string 密文
     */
    public function encrypt($data, $code = ‘base64‘, $padding = OPENSSL_PKCS1_PADDING){
        $ret = false;
        if (!$this->_checkPadding($padding, ‘en‘)) $this->_error(‘padding error‘);
        if (openssl_public_encrypt($data, $result, $this->pubKey, $padding)){
            $ret = $this->_encode($result, $code);
        }
        return $ret;
    } 

    /**
     * 解密
     *
     * @param string 密文
     * @param string 密文编码(base64/hex/bin)
     * @param int 填充方式(OPENSSL_PKCS1_PADDING / OPENSSL_NO_PADDING)
     * @param bool 是否翻转明文(When passing Microsoft CryptoAPI-generated RSA cyphertext, revert the bytes in the block)
     * @return string 明文
     */
    public function decrypt($data, $code = ‘base64‘, $padding = OPENSSL_PKCS1_PADDING, $rev = false){
        $ret = false;
        $data = $this->_decode($data, $code);
        if (!$this->_checkPadding($padding, ‘de‘)) $this->_error(‘padding error‘);
        if ($data !== false){
            if (openssl_private_decrypt($data, $result, $this->priKey, $padding)){
                $ret = $rev ? rtrim(strrev($result), "\0") : ‘‘.$result;
            }
        }
        return $ret;
    } 

    // 私有方法 

    /**
     * 检测填充类型
     * 加密只支持PKCS1_PADDING
     * 解密支持PKCS1_PADDING和NO_PADDING
     *
     * @param int 填充模式
     * @param string 加密en/解密de
     * @return bool
     */
    private function _checkPadding($padding, $type){
        if ($type == ‘en‘){
            switch ($padding){
                case OPENSSL_PKCS1_PADDING:
                    $ret = true;
                    break;
                default:
                    $ret = false;
            }
        } else {
            switch ($padding){
                case OPENSSL_PKCS1_PADDING:
                case OPENSSL_NO_PADDING:
                    $ret = true;
                    break;
                default:
                    $ret = false;
            }
        }
        return $ret;
    } 

    private function _encode($data, $code){
        switch (strtolower($code)){
            case ‘base64‘:
                $data = base64_encode(‘‘.$data);
                break;
            case ‘hex‘:
                $data = bin2hex($data);
                break;
            case ‘bin‘:
            default:
        }
        return $data;
    } 

    private function _decode($data, $code){
        switch (strtolower($code)){
            case ‘base64‘:
                $data = base64_decode($data);
                break;
            case ‘hex‘:
                $data = $this->_hex2bin($data);
                break;
            case ‘bin‘:
            default:
        }
        return $data;
    } 

    private function _getPublicKey($file){
        $key_content = $this->_readFile($file);
        if ($key_content){
            $this->pubKey = openssl_get_publickey($key_content);
        }
    } 

    private function _getPrivateKey($file){
        $key_content = $this->_readFile($file);
        if ($key_content){
            $this->priKey = openssl_get_privatekey($key_content);
        }
    } 

    private function _readFile($file){
        $ret = false;
        if (!file_exists($file)){
            $this->_error("The file {$file} is not exists");
        } else {
            $ret = file_get_contents($file);
        }
        return $ret;
    } 

    private function _hex2bin($hex = false){
        $ret = $hex !== false && preg_match(‘/^[0-9a-fA-F]+$/i‘, $hex) ? pack("H*", $hex) : false;
        return $ret;
    } 

}  

测试示例

<?php
header(‘Content-Type:text/html;Charset=utf-8;‘); 

include "rsa.php"; 

echo ‘<pre>‘;
$a = isset($_GET[‘a‘]) ? $_GET[‘a‘] : ‘测试123‘;
//////////////////////////////////////
$pubfile = ‘E:\ssl\cert\pwd.crt‘;
$prifile = ‘E:\ssl\cert\pwd.pem‘; 

$m = new RSA($pubfile, $prifile);
$x = $m->sign($a);
$y = $m->verify($a, $x);
var_dump($x, $y); 

$x = $m->encrypt($a);
$y = $m->decrypt($x);
var_dump($x, $y);  
时间: 2024-08-28 08:56:43

php RAS加密类代码的相关文章

Discuz论坛写出的php加密解密处理类(代码+使用方法)

PHP加密解密也是常有的事,最近在弄相关的东西,发现discuz论坛里的PHP加密解密处理类代码,感觉挺不错,在用的时候,要参考Discuz论坛的passport相关函数,后面我会附上使用方法,先把类代码帖上来: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 <?php /*

C# RAS 非对称加密类 支持长字符串

/// <summary> /// [email protected] /// </summary> public class MyRAS { /// <summary> /// RAS加密 /// </summary> /// <param name="xmlPublicKey">公钥</param> /// <param name="EncryptString">明文</p

PHP日期操作类代码-农历-阳历转换、闰年、计算天数等

这是一个实用的PHP日期时间操作类,里面包括了公历-农历转换.转换成中文日期格式.计算农历相隔天数.根据阴历年获取生肖.获取阴历月份的天数.获取农历每年的天数.获取闰月.计算阴历日期与正月初一相隔的天数.计算2个公历(阳历)日期之间的天数.根据距离正月初一的天数计算阴历日期.获取天干地支纪年等,PHP日期操作类:Lunar.class.php代码如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

.NET MD5加密解密代码

MD5简介: 是让大容量信息在用数字签名软件签署私人密匙前被"压缩"成一种保密的格式(就是把一个任意长度的字节串变换成一定长的大整数).不管是MD2.MD4还是MD5,它们都需要获得一个随机长度的信息并产生一个128位的信息摘要.虽然这些算法的结构或多或少有些相似,但MD2的设计与MD4和MD5完全不同,那是因为MD2是为8位机器做过设计优化的,而MD4和MD5却是面向32位的电脑.这三个算法的描述和C语言源代码在Internet RFCs 1321中有详细的描述,这是一份最权威的文档

也谈C#之Json,从Json字符串到类代码

原文:也谈C#之Json,从Json字符串到类代码  阅读目录 json转类对象 逆思考 从json字符串自动生成C#类  json转类对象 自从.net 4.0开始,微软提供了一整套的针对json进行处理的方案.其中,就有如何把json字符串转化成C#类对象,其实这段代码很多人都清楚,大家也都认识,我就不多说,先贴代码. 1.添加引用 System.Web.Extensions 2.测试一下代码 1 static class Program 2 { 3 /// <summary> 4 ///

Windows编程 - 开启/关闭/遍历程序的类 代码(C++)

开启/关闭/遍历程序的类 代码(C++) 本文地址: http://blog.csdn.net/caroline_wendy 类包含4个函数, 启动程序, 遍历所有进程, 关闭程序, 遍历进程依赖的动态链接库. 示例: Image.exe是预先生成的可执行程序(exe), 启动程序, 间隔5秒, 关闭程序. 使用方法参加测试程序. 代码: /* * process.h * * Created on: 2014.06.08 * Author: Spike */ /*vs 2012*/ #ifnde

兼容PHP和Java的des加密解密代码分享

这篇文章主要介绍了兼容PHP和Java的des加密解密代码分享,适合如服务器是JAVA语言编写,客户端是PHP编写,并需要des加密解密的情况,需要的朋友可以参考下 php <?php class DES { var $key; var $iv; //偏移量 function DES($key, $iv=0) { $this->key = $key; if($iv == 0) { $this->iv = $key; } else { $this->iv = $iv; } } //加

java文本、表格word转换生成PDF加密文件代码下载

原文:java文本.表格word转换生成PDF加密文件代码下载 代码下载地址:http://www.zuidaima.com/share/1550463239146496.htm 这个实现了PDF加密功能,和一些基本的问题. java文本.表格word转换生成PDF加密文件代码下载,布布扣,bubuko.com

神经网络caffe框架源码解析--softmax_layer.cpp类代码研究

// Copyright 2013 Yangqing Jia // #include <algorithm> #include <vector> #include "caffe/layer.hpp" #include "caffe/vision_layers.hpp" #include "caffe/util/math_functions.hpp" using std::max; namespace caffe { /**