设为首页 收藏本站
查看: 1009|回复: 0

[经验分享] 笔记:des加解密,php和.net版的实现

[复制链接]

尚未签到

发表于 2015-8-23 16:21:09 | 显示全部楼层 |阅读模式
  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 $key
10     * @param string $iv
11     */
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> $value
25     * @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> $value
43     * @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));
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-103098-1-1.html 上篇帖子: PHP笔记(PHP高级篇) 下篇帖子: php框架codeigniter框架源代码分析,注释中文化,类库分析(一)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表