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

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

程序员文章站 2023-02-22 23:11:04
php5.x版本,要添加php扩展php_mcrypt。 php版: 复制代码 代码如下:class std3des {   &...

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));