1. 程式人生 > >php 3DES加密 總有一款適合你

php 3DES加密 總有一款適合你

/**
 * 進行3des ecb 模式加密
 *
 * @param $message
 * @param string $key
 * @return string
 */
public function encode($message){
    $message = $this->pkcs5Pad($message, 8);
if (strlen($message) % 8) {
        $message_padded = str_pad($message,
strlen($message) + 8 - strlen($message) % 8, "\0");
}

    return  
openssl_encrypt($message, 'DES-EDE3', $key = '', OPENSSL_RAW_DATA | OPENSSL_NO_PADDING); } /** * 進行3des ecb 模式加密 * * @param $message * @param string $key * @return string */ public function ecbEncode($message){ $key = ''; $m = MCRYPT_TRIPLEDES; $iv = mcrypt_create_iv(mcrypt_get_iv_size($m,MCRYPT_MODE_ECB
), MCRYPT_RAND); $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_ECB, ''); mcrypt_generic_init($td, $key, $iv); return mcrypt_generic($td,$this->pkcs5_padding($message, 8)); } /** * 進行3des ecb 模式加密 * * @param $message * @param string $key * @return string */ public function ecbEncode1(
$message){ $key = ''; $string = $this->PaddingPKCS7($message); //初始化向量來增加安全性 $td = mcrypt_module_open( MCRYPT_3DES, '', MCRYPT_MODE_ECB, '' ); $iv = mcrypt_create_iv( mcrypt_enc_get_iv_size( $td ), MCRYPT_RAND ); mcrypt_generic_init( $td, $key, $iv ); //開始加密 return mcrypt_generic( $td, $string ); } public function encrypt($text) { $key = ''; $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_TRIPLEDES,MCRYPT_MODE_ECB), MCRYPT_RAND); $text = $this->pkcs5Pad1($text); $td = mcrypt_module_open(MCRYPT_3DES,'',MCRYPT_MODE_ECB,''); mcrypt_generic_init($td,$key,$iv); $data = mcrypt_generic($td, $text); mcrypt_generic_deinit($td); mcrypt_module_close($td); return $data; } /** * 使用pkcs5填充 * * @param $text * @param $blockSize * @return string */ function pkcs5Pad($text, $blockSize) { $pad = $blockSize - (strlen ( $text ) % $blockSize); return $text . str_repeat ( chr ( $pad ), $pad ); } function PaddingPKCS7($input) { $srcdata = $input; $block_size = mcrypt_get_block_size('tripledes', 'ecb'); $padding_char = $block_size - (strlen($input) % $block_size); $srcdata .= str_repeat(chr($padding_char),$padding_char); return $srcdata; } function pkcs5_padding($text, $blocksize) { $pad = $blocksize - (strlen($text) % $blocksize); return $text . str_repeat(chr($pad), $pad); } /** * @param $text * @return string */ private function pkcs5Pad1($text) { $pad = 8 - (strlen($text) % 8); return $text . str_repeat(chr($pad), $pad); }