php实现的rc4加密解密类定义与用法示例
本文实例讲述了php实现的rc4加密解密类。分享给大家供大家参考,具体如下:
class.rc4crypt.php文件:
mode=MCRYPT_ARCFOUR;
break;
casedefined('MCRYPT_RC4');
$this->mode=MCRYPT_RC4;
}
}
}
/**
*Setsthekey.
*
*Keyscanbebetween1and256byteslong.Iftheyarelongerthen256bytes,thefirst256byteswill
*beused.Ifnokeyisexplicitlyset,it'llbeassumedtobeasinglenullbyte.
*
*@accesspublic
*@paramString$key
*/
functionsetKey($key)
{
$this->key=$key;
if(CRYPT_RC4_MODE==CRYPT_RC4_MODE_MCRYPT){
return;
}
$keyLength=strlen($key);
$keyStream=array();
for($i=0;$i<256;$i++){
$keyStream[$i]=$i;
}
$j=0;
for($i=0;$i<256;$i++){
$j=($j+$keyStream[$i]+ord($key[$i%$keyLength]))&255;
$temp=$keyStream[$i];
$keyStream[$i]=$keyStream[$j];
$keyStream[$j]=$temp;
}
$this->encryptIndex=$this->decryptIndex=array(0,0);
$this->encryptStream=$this->decryptStream=$keyStream;
}
/**
*Dummyfunction.
*
*Someprotocols,suchasWEP,prependan"initializationvector"tothekey,effectivelycreatinganewkey[1].
*Ifyouneedtouseaninitializationvectorinthismanner,feelfreetoprependittothekey,yourself,before
*callingsetKey().
*
*[1]WEP'sinitializationvectors(IV's)areusedinasomewhatinsecureway.Since,inthatprotocol,
*theIV'sarerelativelyeasytopredict,anattackdescribedby
*{@linkhttp://www.drizzle.com/~aboba/IEEE/rc4_ksaproc.pdfScottFluhrer,ItsikMantin,andAdiShamir}
*canbeusedtoquicklyguessattherestofthekey.Thefollowinglinkselaborate:
*
*{@linkhttp://www.rsa.com/rsalabs/node.asp?id=2009http://www.rsa.com/rsalabs/node.asp?id=2009}
*{@linkhttp://en.wikipedia.org/wiki/Related_key_attackhttp://en.wikipedia.org/wiki/Related_key_attack}
*
*@paramString$iv
*@seeCrypt_RC4::setKey()
*@accesspublic
*/
functionsetIV($iv)
{
}
/**
*SetsMCryptparameters.(optional)
*
*IfMCryptisbeingused,emptystringswillbeused,unlessotherwisespecified.
*
*@linkhttp://php.net/function.mcrypt-module-open#function.mcrypt-module-open
*@accesspublic
*@paramoptionalInteger$algorithm_directory
*@paramoptionalInteger$mode_directory
*/
functionsetMCrypt($algorithm_directory='',$mode_directory='')
{
if(CRYPT_RC4_MODE==CRYPT_RC4_MODE_MCRYPT){
$this->mcrypt=array($algorithm_directory,$mode_directory);
$this->_closeMCrypt();
}
}
/**
*Encryptsamessage.
*
*@seeCrypt_RC4::_crypt()
*@accesspublic
*@paramString$plaintext
*/
functionencrypt($plaintext)
{
returnself::toHex($this->_crypt($plaintext,CRYPT_RC4_ENCRYPT));
}
/**
*Decryptsamessage.
*
*$this->decrypt($this->encrypt($plaintext))==$this->encrypt($this->encrypt($plaintext)).
*Atleastifthecontinuousbufferisdisabled.
*
*@seeCrypt_RC4::_crypt()
*@accesspublic
*@paramString$ciphertext
*/
functiondecrypt($ciphertext)
{
$ciphertext=self::fromHex($ciphertext);
return$this->_crypt($ciphertext,CRYPT_RC4_DECRYPT);
}
/**
*Encryptsordecryptsamessage.
*
*@seeCrypt_RC4::encrypt()
*@seeCrypt_RC4::decrypt()
*@accessprivate
*@paramString$text
*@paramInteger$mode
*/
function_crypt($text,$mode)
{
if(CRYPT_RC4_MODE==CRYPT_RC4_MODE_MCRYPT){
$keyStream=$mode==CRYPT_RC4_ENCRYPT?'encryptStream':'decryptStream';
if($this->$keyStream===false){
$this->$keyStream=mcrypt_module_open($this->mode,$this->mcrypt[0],MCRYPT_MODE_STREAM,$this->mcrypt[1]);
mcrypt_generic_init($this->$keyStream,$this->key,'');
}elseif(!$this->continuousBuffer){
mcrypt_generic_init($this->$keyStream,$this->key,'');
}
$newText=mcrypt_generic($this->$keyStream,$text);
if(!$this->continuousBuffer){
mcrypt_generic_deinit($this->$keyStream);
}
return$newText;
}
if($this->encryptStream===false){
$this->setKey($this->key);
}
switch($mode){
caseCRYPT_RC4_ENCRYPT:
$keyStream=$this->encryptStream;
list($i,$j)=$this->encryptIndex;
break;
caseCRYPT_RC4_DECRYPT:
$keyStream=$this->decryptStream;
list($i,$j)=$this->decryptIndex;
}
$newText='';
for($k=0;$kcontinuousBuffer){
switch($mode){
caseCRYPT_RC4_ENCRYPT:
$this->encryptStream=$keyStream;
$this->encryptIndex=array($i,$j);
break;
caseCRYPT_RC4_DECRYPT:
$this->decryptStream=$keyStream;
$this->decryptIndex=array($i,$j);
}
}
return$newText;
}
/**
*Treatconsecutive"packets"asiftheyareacontinuousbuffer.
*
*Sayyouhavea16-byteplaintext$plaintext.Usingthedefaultbehavior,thetwofollowingcodesnippets
*willyielddifferentoutputs:
*
*
*echo$rc4->encrypt(substr($plaintext,0,8));
*echo$rc4->encrypt(substr($plaintext,8,8));
*
*
*echo$rc4->encrypt($plaintext);
*
*
*Thesolutionistoenablethecontinuousbuffer.Althoughthiswillresolvetheabovediscrepancy,itcreates
*another,asdemonstratedwiththefollowing:
*
*
*$rc4->encrypt(substr($plaintext,0,8));
*echo$rc4->decrypt($des->encrypt(substr($plaintext,8,8)));
*
*
*echo$rc4->decrypt($des->encrypt(substr($plaintext,8,8)));
*
*
*Withthecontinuousbufferdisabled,thesewouldyieldthesameoutput.Withitenabled,theyyielddifferent
*outputs.Thereasonisduetothefactthattheinitializationvector'schangeaftereveryencryption/
*decryptionroundwhenthecontinuousbufferisenabled.Whenit'sdisabled,theyremainconstant.
*
*Putanotherway,whenthecontinuousbufferisenabled,thestateoftheCrypt_DES()objectchangesaftereach
*encryption/decryptionround,whereasotherwise,it'dremainconstant.Forthisreason,it'srecommendedthat
*continuousbuffersnotbeused.Theydoofferbettersecurityandare,infact,sometimesrequired(SSHusesthem),
*however,theyarealsolessintuitiveandmorelikelytocauseyouproblems.
*
*@seeCrypt_RC4::disableContinuousBuffer()
*@accesspublic
*/
functionenableContinuousBuffer()
{
$this->continuousBuffer=true;
}
/**
*Treatconsecutivepacketsasiftheyareadiscontinuousbuffer.
*
*Thedefaultbehavior.
*
*@seeCrypt_RC4::enableContinuousBuffer()
*@accesspublic
*/
functiondisableContinuousBuffer()
{
if(CRYPT_RC4_MODE==CRYPT_RC4_MODE_INTERNAL){
$this->encryptIndex=$this->decryptIndex=array(0,0);
$this->setKey($this->key);
}
$this->continuousBuffer=false;
}
/**
*Dummyfunction.
*
*SinceRC4isastreamcipherandnotablockcipher,nopaddingisnecessary.Theonlyreasonthisfunctionis
*includedissothatyoucanswitchbetweenablockcipherandastreamciphertransparently.
*
*@seeCrypt_RC4::disablePadding()
*@accesspublic
*/
functionenablePadding()
{
}
/**
*Dummyfunction.
*
*@seeCrypt_RC4::enablePadding()
*@accesspublic
*/
functiondisablePadding()
{
}
/**
*Classdestructor.
*
*Willbecalled,automatically,ifyou'reusingPHP5.Ifyou'reusingPHP4,callityourself.Onlyreally
*needstobecalledifmcryptisbeingused.
*
*@accesspublic
*/
function__destruct()
{
if(CRYPT_RC4_MODE==CRYPT_RC4_MODE_MCRYPT){
$this->_closeMCrypt();
}
}
/**
*ProperlyclosetheMCryptobjects.
*
*@accessprviate
*/
function_closeMCrypt()
{
if($this->encryptStream!==false){
if($this->continuousBuffer){
mcrypt_generic_deinit($this->encryptStream);
}
mcrypt_module_close($this->encryptStream);
$this->encryptStream=false;
}
if($this->decryptStream!==false){
if($this->continuousBuffer){
mcrypt_generic_deinit($this->decryptStream);
}
mcrypt_module_close($this->decryptStream);
$this->decryptStream=false;
}
}
//@functionfromHex把十六进制数转换成字符串
functiontoHex($sa,$len=0){
$buf="";
if($len==0)
$len=strlen($sa);
for($i=0;$i<$len;$i++)
{
$val=dechex(ord($sa{$i}));
if(strlen($val)<2)
$val="0".$val;
$buf.=$val;
}
return$buf;
}
//@functionfromHex把十六进制数转换成字符串
functionfromHex($sa){
$buf="";
$len=strlen($sa);
for($i=0;$i<$len;$i+=2){
$val=chr(hexdec(substr($sa,$i,2)));
$buf.=$val;
}
return$buf;
}
}
使用方法:
include('class.rc4crypt.php');
$rc4=newCrypt_RC4();
$rc4->setKey('21sd54a1w5q');
$text='www.nhooo.com';
echo$x=$rc4->encrypt($text);//加密
echo'
';
echo$rc4->decrypt($x);//解密
运行结果:
7907bb7c6694f179e9642ebd
www.nhooo.com
PS:关于加密解密感兴趣的朋友还可以参考本站在线工具:
在线
文字在线加密解密工具(包含