当前位置: 首页 > 图文教程 > 网络编程 > PHP > 实例应用:使用PHP来进行加密与解密

PHP
MySQL安全性指南
长沙发上的对话(一)
长沙发上的对话(二)
长沙发上的对话(三)
长沙发上的对话(四)
《PHP程序设计》序
《PHP程序设计》第一章 什么是PHP?
PHP4的新特征
php3的ODBC函数
初学入门 PHP 和 MySQL
《PHP程序设计》 第二章 安装PHP
《PHP程序设计》 第三章 PHP中的数据处理
《PHP程序设计》 第四章 程序控制
《PHP程序设计》 第五章 中场一:数据库连接
PHP4中的SESSION管理
开发大型PHP项目的方法(一)
开发大型PHP项目的方法(二)
开发大型PHP项目的方法(三)
开发大型PHP项目的方法(四)
开发大型PHP项目的方法(五)

实例应用:使用PHP来进行加密与解密


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-11-03   浏览: 70 ::
收藏到网摘: n/a

<?php
$key = "This is supposed to be a secret key !!!";
function keyED($txt,$encrypt_key)
{
$encrypt_key = md5($encrypt_key);
$ctr=0;
$tmp = "";
for ($i=0;$i<strlen($txt);$i++)
{
  if ($ctr==strlen($encrypt_key)) $ctr=0;
  $tmp.= substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1);
  $ctr++;
}
return $tmp;
}
function encrypt($txt,$key)
{
srand((double)microtime()*1000000);
$encrypt_key = md5(rand(0,32000));
$ctr=0;
$tmp = "";
for ($i=0;$i<strlen($txt);$i++)
{
  if ($ctr==strlen($encrypt_key)) $ctr=0;
  $tmp.= substr($encrypt_key,$ctr,1) .
  (substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1));
  $ctr++;
}
return keyED($tmp,$key);
}
function decrypt($txt,$key)
{
$txt = keyED($txt,$key);
$tmp = "";
for ($i=0;$i<strlen($txt);$i++)
{
  $md5 = substr($txt,$i,1);
  $i++;
  $tmp.= (substr($txt,$i,1) ^ $md5);
}
return $tmp;
}
$string = "Hello World !!!";
// encrypt $string, and store it in $enc_text
$enc_text = encrypt($string,$key);
// decrypt the encrypted text $enc_text, and store it in $dec_text
$dec_text = decrypt($enc_text,$key);
print "Original text : $string <Br>";
print "Encrypted text : $enc_text <Br>";
print "Decrypted text : $dec_text <Br>";
?>