一段php加密解密的代码

  • A+
所属分类:PHP编程
  1. <?php
  2. $key = "This is supposed to be a secret key !!!";
  3. function keyED($txt,$encrypt_key)
  4. {
  5. $encrypt_key = md5($encrypt_key);
  6. $ctr=0;
  7. $tmp = "";
  8. for ($i=0;$i<strlen($txt);$i++)
  9. {
  10. if ($ctr==strlen($encrypt_key)) $ctr=0;
  11. $tmp.= substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1);
  12. $ctr++;
  13. }
  14. return $tmp;
  15. }
  16. function encrypt($txt,$key)
  17. {
  18. srand((double)microtime()*1000000);
  19. $encrypt_key = md5(rand(0,32000));
  20. $ctr=0;
  21. $tmp = "";
  22. for ($i=0;$i<strlen($txt);$i++)
  23. {
  24. if ($ctr==strlen($encrypt_key)) $ctr=0;
  25. $tmp.= substr($encrypt_key,$ctr,1) .
  26. (substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1));
  27. $ctr++;
  28. }
  29. return keyED($tmp,$key);
  30. }
  31. function decrypt($txt,$key)
  32. {
  33. $txt = keyED($txt,$key);
  34. $tmp = "";
  35. for ($i=0;$i<strlen($txt);$i++)
  36. {
  37. $md5 = substr($txt,$i,1);
  38. $i++;
  39. $tmp.= (substr($txt,$i,1) ^ $md5);
  40. }
  41. return $tmp;
  42. }
  43. $string = "Hello World !!!";
  44. // encrypt $string, and store it in $enc_text  
  45. $enc_text = encrypt($string,$key);
  46. // decrypt the encrypted text $enc_text, and store it in $dec_text  
  47. $dec_text = decrypt($enc_text,$key);
  48. print "Original text : $string <Br>\n";
  49. print "Encrypted text : $enc_text <Br>\n";
  50. print "Decrypted text : $dec_text <Br>\n";
  51. ?>