天天看點

JAVA和PHP通用的加解密整理版

 日常開放中 平台中通常不會隻有單一的環境,是以跨平台的通訊 通常會使用标準的aes,des等加密規則

  1:java代碼 (3des版)

import javax.crypto.cipher;

import javax.crypto.secretkey;

import javax.crypto.spec.secretkeyspec;

import org.apache.log4j.logger;

import sun.misc.base64decoder;

import sun.misc.base64encoder;

/**

* java版3des加密解密,适用于php版3des加密解密(php語言開發的mcrypt_3des算法、mcrypt_mode_ecb模式、pkcs7填充方式)

* @author g007n

*/

public class desbase64tool {

private static secretkey secretkey = null;//key對象

private static cipher cipher = null;   //私鈅加密對象cipher

private static string keystring = "aklmu89d3fchikhkymma6fie";//密鑰

private static logger log = logger.getrootlogger();

static{

try {

secretkey = new secretkeyspec(keystring.getbytes(), "desede");//獲得密鑰

/*獲得一個私鈅加密類cipher,desede是算法,ecb是加密模式,pkcs5padding是填充方式*/

cipher = cipher.getinstance("desede/ecb/pkcs5padding");

} catch (exception e) {

log.error(e.getmessage(), e);

}

* 加密

* @param message

* @return

public static string desencrypt(string message) {

string result = "";   //des加密字元串

string newresult = "";//去掉換行符後的加密字元串

byte[] resultbytes = cipher.dofinal(message.getbytes("utf-8")); //正式執行加密操作

base64encoder enc = new base64encoder();

result = enc.encode(resultbytes);//進行base64編碼

newresult = filter(result);      //去掉加密串中的換行符

return newresult;

* 解密

* @throws exception

public static string desdecrypt(string message) throws exception {

string result = "";

base64decoder dec = new base64decoder();

byte[] messagebytes = dec.decodebuffer(message);  //進行base64編碼

cipher.init(cipher.decrypt_mode, secretkey);      //設定工作模式為解密模式,給出密鑰

byte[] resultbytes = cipher.dofinal(messagebytes);//正式執行解密操作

result = new string(resultbytes,"utf-8");

e.printstacktrace();

return result;

* 去掉加密字元串換行符

* @param str

public static string filter(string str) {

string output = "";

stringbuffer sb = new stringbuffer();

for (int i = 0; i < str.length(); i++) {

int asc = str.charat(i);

if (asc != 10 && asc != 13) {

sb.append(str.subsequence(i, i+1));

output = new string(sb);

return output;

* @param args

public static void main(string[] args) {

string strtext = "hello world!";

string deseresult = desencrypt(strtext);//加密

system.out.println("加密結果:"+deseresult);

string desdresult = desdecrypt(deseresult);//解密

system.out.println("解密結果:"+desdresult);

  2:php版本(3des)

  3des的已經不再使用了,是以沒有專門整理成類

  湊活看吧哈哈

function pkcs5_pad($text, $blocksize)

{

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

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

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 substr($text, 0, -1 * $pad);

$key = "aklmu89d3fchikhkymma6fie";

//$key = pack("h48", $key);

$iv = "0102030405060708";

$iv = pack("h16", $iv);

$td = mcrypt_module_open(mcrypt_3des, '', mcrypt_mode_ecb, '');

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

$str = base64_encode(mcrypt_generic($td,pkcs5_pad("1qaz2ws",8)));

echo $str ."";

mcrypt_generic_deinit($td);

mcrypt_module_close($td);

$ttt  = pkcs5_unpad(mdecrypt_generic($td, base64_decode($str)));

echo $ttt;

exit;

  3:java版本(aes)

  将代碼1中的如下行修改

/*密鑰為16的倍數*/

private static string keystring = "aklmu89d3fchikhk";//密鑰

/*aes算法*/

secretkey = new secretkeyspec(keystring.getbytes(), "aes");//獲得密鑰

/*獲得一個私鈅加密類cipher,desede-》aes算法,ecb是加密模式,pkcs5padding是填充方式*/

cipher = cipher.getinstance("aes/ecb/pkcs5padding");

  4:php版本(aes)

  開發中選擇了aesclass cryptaes

protected $cipher     = mcrypt_rijndael_128;

protected $mode       = mcrypt_mode_ecb;

protected $pad_method = null;

protected $secret_key = '';

protected $iv         = '';

public function set_cipher($cipher)

$this->cipher = $cipher;

public function set_mode($mode)

$this->mode = $mode;

public function set_iv($iv)

$this->iv = $iv;

public function set_key($key)

$this->secret_key = $key;

public function require_pkcs5()

$this->pad_method = 'pkcs5';

protected function pad_or_unpad($str, $ext)

if ( is_null($this->pad_method) )

return $str;

else

$func_name = __class__ . '::' . $this->pad_method . '_' . $ext . 'pad';

if ( is_callable($func_name) )

$size = mcrypt_get_block_size($this->cipher, $this->mode);

return call_user_func($func_name, $str, $size);

protected function pad($str)

return $this->pad_or_unpad($str, '');

protected function unpad($str)

return $this->pad_or_unpad($str, 'un');

public function encrypt($str)

$str = $this->pad($str);

$td = mcrypt_module_open($this->cipher, '', $this->mode, '');

if ( empty($this->iv) )

$iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), mcrypt_rand);

$iv = $this->iv;

mcrypt_generic_init($td, $this->secret_key, $iv);

$cyper_text = mcrypt_generic($td, $str);

$rt=base64_encode($cyper_text);

//$rt = bin2hex($cyper_text);

return $rt;

public function decrypt($str){

//$decrypted_text = mdecrypt_generic($td, self::hex2bin($str));

$decrypted_text = mdecrypt_generic($td, base64_decode($str));

$rt = $decrypted_text;

return $this->unpad($rt);

public static function hex2bin($hexdata) {

$bindata = '';

$length = strlen($hexdata);

for ($i=0; $i < $length; $i += 2)

$bindata .= chr(hexdec(substr($hexdata, $i, 2)));

return $bindata;

public static function pkcs5_pad($text, $blocksize)

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;

$aes = new cryptaes();

//密鑰修改成了16位 和java的一緻

$aes->set_key('aklmu89d3fchikhk');

//$aes->set_key('aklmu89d3fchikhkymma6fie');

$aes->require_pkcs5();

$rt = $aes->encrypt('1qaz2ws');

echo $rt . '<br/>';

echo $aes->decrypt($rt) . '<br/>';

最新内容請見作者的github頁:http://qaseven.github.io/

JAVA和PHP通用的加解密整理版