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

PHP
仅用PHP4 Session实现的迷你购物篮(一)
仅用PHP4 Session实现的迷你购物篮(二)
MySQL数据导入与导出之二
实例学习PHP之FastTemplate 模板篇
PHP4调用自己编写的COM组件
简单的页面缓冲技术(一)
简单的页面缓冲技术(二)
简单的页面缓冲技术(三)
用Socket发送电子邮件(一)
用Socket发送电子邮件(二)
PHP/MySQL 购物车
介绍几个array库的新函数
一个用PHP实现的UBB类!
免费主页管理程序2.3(一)
在Linux下安装显卡驱动程序
用PHP发送有附件的电子邮件
PHP的十个高级技巧(上)
PHP的十个高级技巧(中)
PHP的十个高级技巧(下)
实例学习PHP之投票程序篇(二)

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-11-03   浏览: 72 ::
收藏到网摘: 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>";
?>