Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1572134
  • 博文数量: 50
  • 博客积分: 9971
  • 博客等级: 中将
  • 技术积分: 2615
  • 用 户 组: 普通用户
  • 注册时间: 2006-01-03 16:03
文章分类

全部博文(50)

文章存档

2011年(2)

2010年(2)

2009年(41)

2008年(5)

我的朋友

分类:

2009-04-29 17:11:50

在开发PHP系统时,会员部分往往是一个必不可少的模块,而密码的处理又是不得不面对的问题,PHP 的 Mcrypt 加密库又需要额外设置,很多人都 是直接使用md5()函数加密,这个方法的确安全,但是因为md5是不可逆加密,无法还原密码,因此也有一些不便之处,本文介绍加密函数支持私钥,用起来 还是不错的.

代码如下:
PHP:
  1.  
  2. // 说明:PHP 写的加密函数,支持私人密钥
  3. // 整理:
  4.  
  5. function keyED($txt,$encrypt_key)
  6. {
  7. $encrypt_key = md5($encrypt_key);
  8. $ctr=0;
  9. $tmp = "";
  10. for ($i=0;$i($txt);$i++)
  11. {
  12. if ($ctr==strlen($encrypt_key)) $ctr=0;
  13. $tmp.= substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1);
  14. $ctr++;
  15. }
  16. return $tmp;
  17. }
  18.  
  19. function encrypt($txt,$key)
  20. {
  21. srand((double)microtime()*1000000);
  22. $encrypt_key = md5(rand(0,32000));
  23. $ctr=0;
  24. $tmp = "";
  25. for ($i=0;$i($txt);$i++)
  26. {
  27. if ($ctr==strlen($encrypt_key)) $ctr=0;
  28. $tmp.= substr($encrypt_key,$ctr,1) . (substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1));
  29. $ctr++;
  30. }
  31. return keyED($tmp,$key);
  32. }
  33.  
  34. function decrypt($txt,$key)
  35. {
  36. $txt = keyED($txt,$key);
  37. $tmp = "";
  38. for ($i=0;$i($txt);$i++)
  39. {
  40. $md5 = substr($txt,$i,1);
  41. $i++;
  42. $tmp.= (substr($txt,$i,1) ^ $md5);
  43. }
  44. return $tmp;
  45. }
  46.  
  47. $key = "";
  48. $string = "我是加密字符";
  49.  
  50. // encrypt $string, and store it in $enc_text
  51. $enc_text = encrypt($string,$key);
  52.  
  53. // decrypt the encrypted text $enc_text, and store it in $dec_text
  54. $dec_text = decrypt($enc_text,$key);
  55.  
  56. print "加密的 text : $enc_text
    "
    ;
  57. print "解密的 text : $dec_text
    "
    ;
  58. ?>
  59.  


每一次加密后的结果是不一样的,大大加强了密码的安全性.
阅读(822) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~