Implementation method of des encryption and decryption in PHP and .net_PHP tutorial

WBOY
Release: 2016-07-21 15:13:13
Original
1194 people have browsed it

For php5.x version, add php extension php_mcrypt.

PHP version:

Copy code The code is as follows:

class STD3Des
 {
     private $key = "";
     private $iv = "";

     /**
* Construct, pass two base64_encoded KEY and 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 $value
     * @return
    */
     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 $value
     * @return
    */
     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);
     }
 }


//Use
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.'
';
$rs2=$des->decrypt($rs1);
echo $rs2;

.net version

Copy code The code is as follows:

sealed public class CryptoHelper
 {
     ///
     /// Encrypts the specified input.
     ///

     /// The input.
     /// key
     /// iv
     ///
     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;
     }
     ///
     /// Decrypts the specified input.
     ///

     /// the input.
     /// key
     /// iv
     ///
     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));

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/326574.htmlTechArticlephp5.x版本,要添加php扩展php_mcrypt。 PHP版: 复制代码 代码如下: class STD3Des { private $key = ""; private $iv = ""; /** * 构造,传递二个已经进行base...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!