程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP基礎知識 >> php DES/DES3加密解密算法

php DES/DES3加密解密算法

編輯:PHP基礎知識
 

DES.class.php
<?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<strlen($h); $a+=2) {
$r.=chr(hexdec($h{$a}.$h{($a+1)}));
}
return $r;
}
}
?>
 

 
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved