首頁 >後端開發 >php教程 >笔记:des加解密,php和.net版的实现

笔记:des加解密,php和.net版的实现

WBOY
WBOY原創
2016-06-23 14:37:391053瀏覽

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

 1 class STD3Des 2 { 3     private $key = ""; 4     private $iv = ""; 5  6     /** 7     * 构造,传递二个已经进行base64_encode的KEY与IV 8     * 9     * @param string $key10     * @param string $iv11     */12     function __construct ($key, $iv)13     {14         if (empty($key) || empty($iv)) {15             echo 'key and iv is not valid';16             exit();17         }18         $this->key = $key;19         $this->iv = $iv;20     }21 22     /**23     *加密24     * @param <type> $value25     * @return <type>26     */27     public function encrypt ($value)28     {29         $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');30         $iv = base64_decode($this->iv);31         $value = $this->PaddingPKCS7($value);32         $key = base64_decode($this->key);33         mcrypt_generic_init($td, $key, $iv);34         $ret = base64_encode(mcrypt_generic($td, $value));35         mcrypt_generic_deinit($td);36         mcrypt_module_close($td);37         return $ret;38     }39 40     /**41     *解密42     * @param <type> $value43     * @return <type>44     */45     public function decrypt ($value)46     {47         $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');48         $iv = base64_decode($this->iv);49         $key = base64_decode($this->key);50         mcrypt_generic_init($td, $key, $iv);51         $ret = trim(mdecrypt_generic($td, base64_decode($value)));52         $ret = $this->UnPaddingPKCS7($ret);53         mcrypt_generic_deinit($td);54         mcrypt_module_close($td);55         return $ret;56     }57 58     private function PaddingPKCS7 ($data)59     {60         $block_size = mcrypt_get_block_size('tripledes', 'cbc');61         $padding_char = $block_size - (strlen($data) % $block_size);62         $data .= str_repeat(chr($padding_char), $padding_char);63         return $data;64     }65 66     private function UnPaddingPKCS7($text)67     {68         $pad = ord($text{strlen($text) - 1});69         if ($pad > strlen($text)) {70             return false;71         }72         if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) {73             return false;74         }75         return substr($text, 0, - 1 * $pad);76     }77 }78 79 80 //使用81 include('STD3Des.class.php');82 $key='abcdefgh';83 $iv='abcdefgh';84 $msg='test string';85 $des=new STD3Des(base64_encode($key),base64_encode($iv));86 $rs1=$des->encrypt($msg);87 echo $rs1.'<br />';88 $rs2=$des->decrypt($rs1);89 echo $rs2;

 

.net版本

  1 sealed public class CryptoHelper  2 {  3     /// <summary>  4     /// Encrypts the specified input.  5     /// </summary>  6     /// <param name="input">The input.</param>  7     /// <param name="key">key</param>  8     /// <param name="iv">iv</param>  9     /// <returns></returns> 10     public static string EncryptDes(string input, byte[] key, byte[] iv) 11     { 12         if (input == null || input.Length == 0) 13             return String.Empty; 14  15         DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 16         MemoryStream ms = null; 17         CryptoStream encStream = null; 18         StreamWriter sw = null; 19         string result = String.Empty; 20  21         try 22         { 23             ms = new MemoryStream(); 24  25             // Create a CryptoStream using the memory stream and the  26             // CSP DES key.   27             //des.Mode = CipherMode.CBC; 28             //des.Padding = PaddingMode.PKCS7;   29             encStream = new CryptoStream(ms, des.CreateEncryptor(key, iv), CryptoStreamMode.Write); 30  31             // Create a StreamWriter to write a string 32             // to the stream. 33             sw = new StreamWriter(encStream); 34  35             // Write the plaintext to the stream. 36             sw.Write(input); 37  38             sw.Flush(); 39             encStream.FlushFinalBlock(); 40             ms.Flush(); 41  42  43             result = Convert.ToBase64String(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length, CultureInfo.InvariantCulture)); 44         } 45         finally 46         { 47             //close objects 48             if (sw != null) 49                 sw.Close(); 50             if (encStream != null) 51                 encStream.Close(); 52             if (ms != null) 53                 ms.Close(); 54         } 55  56         // Return the encrypted string 57         return result; 58     } 59     /// <summary> 60     /// Decrypts the specified input. 61     /// </summary> 62     /// <param name="input">the input.</param> 63     /// <param name="key">key</param> 64     /// <param name="iv">iv</param> 65     /// <returns></returns> 66     public static string DecryptDes(string input, byte[] key, byte[] iv) 67     { 68         byte[] buffer; 69         try { buffer = Convert.FromBase64String(input); } 70         catch (System.ArgumentNullException) { return String.Empty; } 71         // length is zero, or not an even multiple of four (plus a few other cases) 72         catch (System.FormatException) { return String.Empty; } 73  74         DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 75         MemoryStream ms = null; 76         CryptoStream encStream = null; 77         StreamReader sr = null; 78         string result = String.Empty; 79  80         try 81         { 82             ms = new MemoryStream(buffer); 83  84             // Create a CryptoStream using the memory stream and the  85             // CSP DES key.  86             encStream = new CryptoStream(ms, des.CreateDecryptor(key, iv), CryptoStreamMode.Read); 87  88             // Create a StreamReader for reading the stream. 89             sr = new StreamReader(encStream); 90  91             // Read the stream as a string. 92             result = sr.ReadToEnd(); 93         } 94         finally 95         { 96             //close objects 97             if (sr != null) 98                 sr.Close(); 99             if (encStream != null)100                 encStream.Close();101             if (ms != null)102                 ms.Close();103         }104 105         return result;106     }107 }108 109 110 //调用111 112 string key = "abcdefgh";113 string iv = "abcdefgh";114 string msg="test string";115 string rs1 = CryptoHelper.EncryptDes(msg, System.Text.Encoding.ASCII.GetBytes(key), System.Text.Encoding.ASCII.GetBytes(iv));116 string rs2 = CryptoHelper.DecryptDes(rs1, System.Text.Encoding.ASCII.GetBytes(key), System.Text.Encoding.ASCII.GetBytes(iv));

 

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn