php des3加密解密,php DES/DES3加密解密算法

DES.class.php

class DES{

public static function Encrypt($key,$text){

$size = mcrypt_get_block_size('des','ecb');

$text = self::pkcs5_pad($text, $size);

$td = mcrypt_module_open('des', '', 'ecb', '');

//srand((double)microtime() * 1000000);

$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);

mcrypt_generic_init($td, $key, $iv);

$data = mcrypt_generic($td, $text);

mcrypt_generic_deinit($td);

mcrypt_module_close($td);

$data = base64_encode($data);

return $data;

}

public static function Decrypt($key,$encrypted){

$encrypted = base64_decode($encrypted);

$td = mcrypt_module_open('des','','ecb','');

//srand((double)microtime() * 1000000);

$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);

$ks = mcrypt_enc_get_key_size($td);

mcrypt_generic_init($td, $key, $iv);

$decrypted = mdecrypt_generic($td, $encrypted);

mcrypt_generic_deinit($td);

mcrypt_module_close($td);

$plain_text=self::pkcs5_unpad($decrypted);

return $plain_text;

}

public static function pkcs5_pad ($text, $blocksize){

$pad = $blocksize - (strlen($text) % $blocksize);

return $text . str_repeat(chr($pad), $pad);

}

public static function pkcs5_unpad($text){

$pad = ord($text{strlen($text)-1});

if ($pad > strlen($text)){

return false;

}

if (strspn($text, chr($pad), strlen($text) - $pad) != $pad){

return false;

}

return substr($text, 0, -1 * $pad);

}

}

3DES加密解密!TripleDES.class.php

Class TripleDES{

public static function Encrypt($key,$text){

$cipher = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_ECB, '');

srand((double)microtime() * 1000000);

$size=mcrypt_enc_get_iv_size($cipher);

$iv = mcrypt_create_iv($size, MCRYPT_RANDOM);

if(mcrypt_generic_init($cipher, $key, $iv) != -1){

$cipherText = mcrypt_generic($cipher,$text);

mcrypt_generic_deinit($cipher);

return bin2hex($cipherText);

}

}

public static function Decrypt($key,$encryptedText){

$cipherText=self::Hex2bin($encryptedText);

$cipher = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_ECB, '');

srand((double)microtime() * 1000000);

$size=mcrypt_enc_get_iv_size($cipher);

$iv = mcrypt_create_iv($size, MCRYPT_RAND);

if (mcrypt_generic_init($cipher, $key, $iv) != -1){

$decrypted_data = mdecrypt_generic($cipher,$cipherText);

mcrypt_generic_deinit($cipher);

return $decrypted_data;

}

}

public static function Hex2bin($h){

if (!is_string($h)) return null;

$r='';

for ($a=0; $a

$r.=chr(hexdec($h{$a}.$h{($a+1)}));

}

return $r;

}

}

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值