qileilove

          blog已經轉移至github,大家請訪問 http://qaseven.github.io/

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

            日常開放中 平臺中通常不會只有單一的環境,因此跨平臺的通訊 通常會使用標準的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)

            開發中選擇了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);
          }
          }
          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;

          posted on 2013-09-16 10:00 順其自然EVO 閱讀(8213) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          <2013年9月>
          25262728293031
          1234567
          891011121314
          15161718192021
          22232425262728
          293012345

          導航

          統計

          常用鏈接

          留言簿(55)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 安多县| 怀来县| 玛纳斯县| 隆德县| 泽州县| 苗栗市| 当涂县| 沿河| 乳山市| 迁安市| 滕州市| 比如县| 桃园市| 仙居县| 中方县| 陇川县| 大城县| 英吉沙县| 利川市| 江陵县| 景德镇市| 修水县| 石家庄市| 安康市| 广东省| 甘南县| 阳高县| 汕头市| 鹤岗市| 遂宁市| 阳谷县| 汤原县| 琼海市| 满洲里市| 珠海市| 达日县| 六安市| 章丘市| 南川市| 松桃| 西乌|