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

2015-01-24信息快讯网

PHP和.net中des加解密的实现方法,需要的朋友可以参考一下

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中怎样保持SESSION不过期 原理及方案介绍
php中用socket模拟http中post或者get提交数据的示例代码
怎样使用php与jquery设置和读取cookies
php addslashes 利用递归实现使用反斜线引用字符串
注意:php5.4删除了session_unregister函数
浅析PHP Socket技术
深入解析Session是否必须依赖Cookie
请离开include_once和require_once
解析PHP中的unset究竟会不会释放内存
实测在class的function中include的文件中非php的global全局环境
解析:php调用MsSQL存储过程使用内置RETVAL获取过程中的return值
php修改NetBeans默认字体的大小
浅析PHP中的UNICODE 编码与解码
浅析HTTP消息头网页缓存控制以及header常用指令介绍
php连接函数implode与分割explode的深入解析
PHP使用DES进行加密与解密的方法详解
基于session_unset与session_destroy的区别详解
PHP人民币金额数字转中文大写的函数代码
php和js如何通过json互相传递数据相关问题探讨
php字符串分割函数explode的实例代码
php中使用addslashes函数报错问题的解决方法
php中设置index.php文件为只读的方法
set_include_path和get_include_path使用及注意事项
破解.net程序(dll文件)编译和反编译方法
PHP5.4中json_encode中文转码的变化小结
PHP中CURL方法curl_setopt()函数的参数分享
mysqli_set_charset和SET NAMES使用抉择及优劣分析
PHP中header和session_start前不能有输出原因分析
整理的一些实用WordPress后台MySQL操作命令
将博客园(cnblogs.com)数据导入到wordpress的代码
PDO版本问题 Invalid parameter number: no parameters were bound
php中3des加密代码(完全与.net中的兼容)
通过PHP的内置函数,通过DES算法对数据加密和解密
©2014-2024 dbsqp.com