欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php实现和c#一致的DES加密解密实例

程序员文章站 2024-03-11 19:26:37
php实现和c#一致的des加密解密,可以从网上搜到一大堆,但是测试后发现都没法用。以下正确代码是我经过苦苦才找到的。希望大家在系统整合时能用的上。 注意:key的长度为...

php实现和c#一致的des加密解密,可以从网上搜到一大堆,但是测试后发现都没法用。以下正确代码是我经过苦苦才找到的。希望大家在系统整合时能用的上。

注意:key的长度为8位以内。

//c# 版des 加解密算法 
using system;   
using system.data;   
using system.configuration;   
using system.web;   
using system.web.security;   
using system.web.ui;   
using system.web.ui.webcontrols;   
using system.web.ui.webcontrols.webparts;   
using system.web.ui.htmlcontrols;   
using system.data.sqlclient;   
using system.security.cryptography;   
using system.io;   
using system.text;   
public class des{   
  //加解密密钥 
  private static string skey = "12345678"; 
  //初始化向量 
  private static byte[] desiv = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };  
  
        #region desencode des加密   
        public static string desencode(string ptoencrypt, string skey)   
        {   
          ptoencrypt = httpcontext.current.server.urlencode(ptoencrypt);   
          descryptoserviceprovider des = new descryptoserviceprovider();   
          byte[] inputbytearray = encoding.getencoding("utf-8").getbytes(ptoencrypt);   
         
          //建立加密对象的密钥和偏移量   
          //原文使用asciiencoding.ascii方法的getbytes方法   
          //使得输入密码必须输入英文文本   
          des.key = asciiencoding.ascii.getbytes(skey);   
          des.iv = asciiencoding.ascii.getbytes(skey);   
          memorystream ms = new memorystream();   
          cryptostream cs = new cryptostream(ms, des.createencryptor(), cryptostreammode.write);   
         
          cs.write(inputbytearray, 0, inputbytearray.length);   
          cs.flushfinalblock();   
         
          stringbuilder ret = new stringbuilder();   
          foreach (byte b in ms.toarray())   
          {   
            ret.appendformat("{0:x2}", b);   
          }   
          ret.tostring();   
          return ret.tostring();   
        }  
        #endregion  
        /// <summary> 
        ///  
        /// </summary> 
        /// <param name="ptodecrypt"> 待解密的字符串</param> 
        /// <param name="skey"> 解密密钥,要求为8字节,和加密密钥相同</param> 
        /// <returns>解密成功返回解密后的字符串,失败返源串</returns> 
        #region desdecode des解密 
        public static string desdecode(string ptodecrypt, string skey) 
        { 
          //  httpcontext.current.response.write(ptodecrypt + "<br>" + skey);   
          //  httpcontext.current.response.end();   
          descryptoserviceprovider des = new descryptoserviceprovider(); 
        
          byte[] inputbytearray = new byte[ptodecrypt.length / 2]; 
          for (int x = 0; x < ptodecrypt.length / 2; x++) 
          { 
            int i = (convert.toint32(ptodecrypt.substring(x * 2, 2), 16)); 
            inputbytearray[x] = (byte)i; 
          } 
        
          des.key = asciiencoding.ascii.getbytes(skey); 
          des.iv = asciiencoding.ascii.getbytes(skey); 
          memorystream ms = new memorystream(); 
          cryptostream cs = new cryptostream(ms, des.createdecryptor(), cryptostreammode.write); 
          cs.write(inputbytearray, 0, inputbytearray.length); 
          cs.flushfinalblock(); 
        
          stringbuilder ret = new stringbuilder(); 
        
          return httpcontext.current.server.urldecode(system.text.encoding.default.getstring(ms.toarray())); 
        } 
  #endregion  
}  
<?php 
class des 
{ 
  var $key; 
  var $iv; //偏移量 
   
  function des( $key, $iv=0 ) { 
  //key长度8例如:1234abcd 
    $this->key = $key; 
    if( $iv == 0 ) { 
      $this->iv = $key; //默认以$key 作为 iv 
    } else { 
      $this->iv = $iv; //mcrypt_create_iv ( mcrypt_get_block_size (mcrypt_des, mcrypt_mode_cbc), mcrypt_dev_random ); 
    } 
  } 
   
  function encrypt($str) { 
  //加密,返回大写十六进制字符串 
    $size = mcrypt_get_block_size ( mcrypt_des, mcrypt_mode_cbc ); 
    $str = $this->pkcs5pad ( $str, $size ); 
    return strtoupper( bin2hex( mcrypt_cbc(mcrypt_des, $this->key, $str, mcrypt_encrypt, $this->iv ) ) ); 
  } 
   
  function decrypt($str) { 
  //解密 
    $strbin = $this->hex2bin( strtolower( $str ) ); 
    $str = mcrypt_cbc( mcrypt_des, $this->key, $strbin, mcrypt_decrypt, $this->iv ); 
    $str = $this->pkcs5unpad( $str ); 
    return $str; 
  } 
   
  function hex2bin($hexdata) { 
    $bindata = ""; 
    for($i = 0; $i < strlen ( $hexdata ); $i += 2) { 
      $bindata .= chr ( hexdec ( substr ( $hexdata, $i, 2 ) ) ); 
    } 
    return $bindata; 
  } 
 
  function pkcs5pad($text, $blocksize) { 
    $pad = $blocksize - (strlen ( $text ) % $blocksize); 
    return $text . str_repeat ( chr ( $pad ), $pad ); 
  } 
   
  function pkcs5unpad($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 ); 
  } 
   
} 
?> 

以上这篇php实现和c#一致的des加密解密实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。