<?php /** * Class DES * 仅支持秘钥SIZE为8位 模式为ECB */ class DES { public static function encrypt($input, $key) { $block = mcrypt_get_block_size('des', 'ecb'); $pad = $block - (strlen($input) % $block); $input .= str_repeat(chr($pad), $pad); return base64_encode(mcrypt_encrypt(MCRYPT_DES, $key, $input, MCRYPT_MODE_ECB)); } public static function decrypt($sStr, $sKey) { $decrypted = mcrypt_decrypt(MCRYPT_DES, $sKey, base64_decode($sStr), MCRYPT_MODE_ECB); $dec_s = strlen($decrypted); $padding = ord($decrypted[$dec_s-1]); $decrypted = substr($decrypted, 0, -$padding); return $decrypted; } }
使用方法:
//加密:
$result = json_encode($data);
$result = DES::encrypt($result, $key);
print_r($result);
//解密:
$result = DES::decrypt($result, $key);
print_r($result);