自己整理的php带密钥的加密解密类

在有些时候我们需要存贮到数据库中的内容是加密信息,比如 password,money 等敏感信息,以提高安全等级,

这里是一个带公钥的加密解密程序 ,测试是不错性能的, 

<?php
/*
字符串加密解密函数,用于mysql存贮加密解密信息
*/
class  MyClass_Crypt{
   
    //公钥
    protected $key = “123456”; 

    private 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;
    }

//$txt 是需要加密的字符串   
    public function encrypt($txt,$key=”)
    {
        if(empty($key))
            $key=$this->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 $this->keyED($tmp,$key);
    }

//$txt 是需要解密的字符串   
    public function decrypt($txt,$key=”)
    {
        if(empty($key))
            $key=$this->key;
       
        $txt = $this->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;
    }

    public function setKey($key)
    {
        if(empty($key))
            return Null;
       
        $this->key=$key;
    }

    public function getKey()
    {
        return $this->key;
    }
   
}
/*
$string = “123456”;
$crypt= new Crypt;
echo $crypt->getKey().'<br>’;
$crypt->setKey(‘sdfsd’);
echo $crypt->getKey().'<br>’;

// encrypt $string, and store it in $enc_text
$enc_text = $crypt->encrypt($string);

// decrypt the encrypted text $enc_text, and store it in $dec_text
$dec_text = $crypt->decrypt($enc_text);
print “Original text : $string<br>\n”;
print “Encrypted text : $enc_text<br>\n”;
print “Decrypted text : $dec_text\n”;
*/
?>