PHP和.net中des加解密的实现方法


Posted in PHP onFebruary 27, 2013

php5.x版本,要添加php扩展php_mcrypt。

PHP版:

class STD3Des
 {
     private $key = "";
     private $iv = "";     /**
     * 构造,传递二个已经进行base64_encode的KEY与IV
     *
     * @param string $key
     * @param string $iv
     */
     function __construct ($key, $iv)
     {
         if (empty($key) || empty($iv)) {
             echo 'key and iv is not valid';
             exit();
         }
         $this->key = $key;
         $this->iv = $iv;
     }
     /**
     *加密
     * @param <type> $value
     * @return <type>
     */
     public function encrypt ($value)
     {
         $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
         $iv = base64_decode($this->iv);
         $value = $this->PaddingPKCS7($value);
         $key = base64_decode($this->key);
         mcrypt_generic_init($td, $key, $iv);
         $ret = base64_encode(mcrypt_generic($td, $value));
         mcrypt_generic_deinit($td);
         mcrypt_module_close($td);
         return $ret;
     }
     /**
     *解密
     * @param <type> $value
     * @return <type>
     */
     public function decrypt ($value)
     {
         $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
         $iv = base64_decode($this->iv);
         $key = base64_decode($this->key);
         mcrypt_generic_init($td, $key, $iv);
         $ret = trim(mdecrypt_generic($td, base64_decode($value)));
         $ret = $this->UnPaddingPKCS7($ret);
         mcrypt_generic_deinit($td);
         mcrypt_module_close($td);
         return $ret;
     }
     private function PaddingPKCS7 ($data)
     {
         $block_size = mcrypt_get_block_size('tripledes', 'cbc');
         $padding_char = $block_size - (strlen($data) % $block_size);
         $data .= str_repeat(chr($padding_char), $padding_char);
         return $data;
     }
     private function UnPaddingPKCS7($text)
     {
         $pad = ord($text{strlen($text) - 1});
         if ($pad > strlen($text)) {
             return false;
         }
         if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) {
             return false;
         }
         return substr($text, 0, - 1 * $pad);
     }
 }
 
 //使用
 include('STD3Des.class.php');
 $key='abcdefgh';
 $iv='abcdefgh';
 $msg='test string';
 $des=new STD3Des(base64_encode($key),base64_encode($iv));
 $rs1=$des->encrypt($msg);
 echo $rs1.'<br />';
 $rs2=$des->decrypt($rs1);
 echo $rs2;

.net版本

sealed public class CryptoHelper
 {
     /// <summary>
     /// Encrypts the specified input.
     /// </summary>
     /// <param name="input">The input.</param>
     /// <param name="key">key</param>
     /// <param name="iv">iv</param>
     /// <returns></returns>
     public static string EncryptDes(string input, byte[] key, byte[] iv)
     {
         if (input == null || input.Length == 0)
             return String.Empty;         DESCryptoServiceProvider des = new DESCryptoServiceProvider();
         MemoryStream ms = null;
         CryptoStream encStream = null;
         StreamWriter sw = null;
         string result = String.Empty;
         try
         {
             ms = new MemoryStream();
             // Create a CryptoStream using the memory stream and the 
             // CSP DES key.  
             //des.Mode = CipherMode.CBC;
             //des.Padding = PaddingMode.PKCS7;  
             encStream = new CryptoStream(ms, des.CreateEncryptor(key, iv), CryptoStreamMode.Write);
             // Create a StreamWriter to write a string
             // to the stream.
             sw = new StreamWriter(encStream);
             // Write the plaintext to the stream.
             sw.Write(input);
             sw.Flush();
             encStream.FlushFinalBlock();
             ms.Flush();
 
             result = Convert.ToBase64String(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length, CultureInfo.InvariantCulture));
         }
         finally
         {
             //close objects
             if (sw != null)
                 sw.Close();
             if (encStream != null)
                 encStream.Close();
             if (ms != null)
                 ms.Close();
         }
         // Return the encrypted string
         return result;
     }
     /// <summary>
     /// Decrypts the specified input.
     /// </summary>
     /// <param name="input">the input.</param>
     /// <param name="key">key</param>
     /// <param name="iv">iv</param>
     /// <returns></returns>
     public static string DecryptDes(string input, byte[] key, byte[] iv)
     {
         byte[] buffer;
         try { buffer = Convert.FromBase64String(input); }
         catch (System.ArgumentNullException) { return String.Empty; }
         // length is zero, or not an even multiple of four (plus a few other cases)
         catch (System.FormatException) { return String.Empty; }
         DESCryptoServiceProvider des = new DESCryptoServiceProvider();
         MemoryStream ms = null;
         CryptoStream encStream = null;
         StreamReader sr = null;
         string result = String.Empty;
         try
         {
             ms = new MemoryStream(buffer);
             // Create a CryptoStream using the memory stream and the 
             // CSP DES key. 
             encStream = new CryptoStream(ms, des.CreateDecryptor(key, iv), CryptoStreamMode.Read);
             // Create a StreamReader for reading the stream.
             sr = new StreamReader(encStream);
             // Read the stream as a string.
             result = sr.ReadToEnd();
         }
         finally
         {
             //close objects
             if (sr != null)
                 sr.Close();
             if (encStream != null)
                 encStream.Close();
             if (ms != null)
                 ms.Close();
         }
         return result;
     }
 }
 
 //调用
 string key = "abcdefgh";
 string iv = "abcdefgh";
 string msg="test string";
 string rs1 = CryptoHelper.EncryptDes(msg, System.Text.Encoding.ASCII.GetBytes(key), System.Text.Encoding.ASCII.GetBytes(iv));
 string rs2 = CryptoHelper.DecryptDes(rs1, System.Text.Encoding.ASCII.GetBytes(key), System.Text.Encoding.ASCII.GetBytes(iv));
PHP 相关文章推荐
PHP 导出数据到淘宝助手CSV的方法分享
Feb 27 PHP
php检测useragent版本示例
Mar 24 PHP
PHP实现把MySQL数据库导出为.sql文件实例(仿PHPMyadmin导出功能)
May 10 PHP
PHP使用xmllint命令处理xml与html的方法
Dec 15 PHP
PHP实现动态web服务器方法
Jul 29 PHP
Centos6.5和Centos7 php环境搭建方法
May 27 PHP
PHP简单获取随机数的常用方法小结
Jun 07 PHP
PHP实现限制IP访问及提交次数的方法详解
Jul 17 PHP
PHPExcel 修改已存在Excel的方法
May 03 PHP
PHP实现微信商户支付企业付款到零钱功能
Sep 30 PHP
phpstorm 配置xdebug的示例代码
Mar 31 PHP
PHP正则表达式函数preg_replace用法实例分析
Jun 04 PHP
php和js如何通过json互相传递数据相关问题探讨
Feb 26 #PHP
php数组的概述及分类与声明代码演示
Feb 26 #PHP
浅谈apache和nginx的rewrite的区别
Feb 22 #PHP
php并发对MYSQL造成压力的解决方法
Feb 21 #PHP
php连接mssql数据库的几种方法
Feb 21 #PHP
PHP递归调用的小技巧讲解
Feb 19 #PHP
PHP递归返回值时出现的问题解决办法
Feb 19 #PHP
You might like
Protoss热键控制
2020/03/14 星际争霸
PHPMailer邮件发送的实现代码
2013/05/04 PHP
PHP编译安装中遇到的两个错误和解决方法
2014/08/20 PHP
PHP脚本监控Nginx 502错误并自动重启php-fpm
2015/05/13 PHP
总结的一些PHP开发中的tips(必看篇)
2017/03/24 PHP
Laravel使用Queue队列的技巧汇总
2019/09/02 PHP
javascript 类型判断代码分析
2010/03/28 Javascript
jQuery boxy弹出层插件中文演示及使用讲解
2011/02/24 Javascript
javascript实现playfair和hill密码算法
2014/12/07 Javascript
PHPExcel中的一些常用方法汇总
2015/01/23 Javascript
解决js函数闭包内存泄露问题的办法
2016/01/25 Javascript
jQuery图片轮播插件——前端开发必看
2016/05/31 Javascript
微信小程序 触控事件详细介绍
2016/10/17 Javascript
JavaScript实现解析INI文件内容的方法
2016/11/17 Javascript
基于vue实现swipe分页组件实例
2017/05/25 Javascript
浅谈HTTP 缓存的那些事儿
2018/10/17 Javascript
详解小程序中h5页面onShow实现及跨页面通信方案
2019/05/30 Javascript
node静态服务器实现静态读取文件或文件夹
2019/12/03 Javascript
vue data变量相互赋值后被实时同步的解决步骤
2020/08/05 Javascript
[01:12:44]VG vs Mineski Supermajor 败者组 BO3 第二场 6.6
2018/06/07 DOTA
Python中操作符重载用法分析
2016/04/29 Python
Python退火算法在高次方程的应用
2018/07/26 Python
Django使用paginator插件实现翻页功能的实例
2018/10/24 Python
python实现图片转字符小工具
2019/04/30 Python
Django CBV类的用法详解
2019/07/26 Python
Django 后台获取文件列表 InMemoryUploadedFile的例子
2019/08/07 Python
Python如何访问字符串中的值
2020/02/09 Python
Pytho爬虫中Requests设置请求头Headers的方法
2020/09/22 Python
分享一个H5原生form表单的checkbox特效代码
2018/02/26 HTML / CSS
html5 canvas 画图教程案例分析
2012/11/23 HTML / CSS
美国在线精品家居网站:Burke Decor
2017/04/12 全球购物
儿科护士实习自我鉴定
2013/10/17 职场文书
优秀体育委员自荐书
2014/01/31 职场文书
绿色校园广播稿
2014/10/13 职场文书
浅析NIO系列之TCP
2021/06/15 Java/Android
java调用Restful接口的三种方法
2021/08/23 Java/Android