JAVA和PHP通用的加解密整理版(AES,DES…)

来源:互联网 发布:easycms 建站 编辑:程序博客网 时间:2024/06/17 18:51

JAVA和PHP通用的加解密整理版(AES,DES…)



日常开放中 平台中通常不会只有单一的环境,因此跨平台的通讯 通常会使用标准的AES,DES等加密规则

公司的项目开发中 遇到了JAVA和PHP的加密解密跨平台的问题 经过多方查找资料以及研究找出一个通用的基础加解密方案如下

 

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 = "";//去掉换行符后的加密字符串     try {      cipher.init(Cipher.ENCRYPT_MODE, secretKey);     //设置工作模式为加密模式,给出密钥      byte[] resultBytes = cipher.doFinal(message.getBytes("UTF-8")); //正式执行加密操作      BASE64Encoder enc = new BASE64Encoder();   result = enc.encode(resultBytes);//进行BASE64编码   newResult = filter(result);      //去掉加密串中的换行符  } catch (Exception e) {   log.error(e.getMessage(), e);  }  return newResult;    } /**  * 解密  * @param message  * @return  * @throws Exception  */    public static String desDecrypt(String message) throws Exception {     String result = "";     try {            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");  } catch (Exception e) {   e.printStackTrace();  }  return result;    } /**  * 去掉加密字符串换行符  * @param str  * @return  */ 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) {  try {   String strText = "Hello world!";   String deseResult = desEncrypt(strText);//加密   System.out.println("加密结果:"+deseResult);   String desdResult = desDecrypt(deseResult);//解密   System.out.println("解密结果:"+desdResult);  } catch (Exception e) {   e.printStackTrace();  } }}
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 false;  }  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);  $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_ECB, '');mcrypt_generic_init($td, $key, $iv);$ttt  = pkcs5_unpad(mdecrypt_generic($td, base64_decode($str)));mcrypt_generic_deinit($td);mcrypt_module_close($td);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)
   开发中选择了AES
class 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);            }        }        return $str;    }    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);        }        else        {            $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);        mcrypt_generic_deinit($td);        mcrypt_module_close($td);        return $rt;    }    public function decrypt($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);        }        else        {            $iv = $this->iv;        }        mcrypt_generic_init($td, $this->secret_key, $iv);        //$decrypted_text = mdecrypt_generic($td, self::hex2bin($str));        $decrypted_text = mdecrypt_generic($td, base64_decode($str));        $rt = $decrypted_text;        mcrypt_generic_deinit($td);        mcrypt_module_close($td);        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)    {        $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);    }}$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/>';exit;

转载:http://kimwu.sinaapp.com/2011/11/11/java和php通用的加解密整理版(aesdes-)/
原创粉丝点击