package com.lordcard.network.socket;
import java.io.*;
import java.security.Key;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;

public class HURLEncoder {

	 public static String readUTF(String s){
		 if(s == null || s.equals(""))return s;
	     StringBuffer strBuf = new StringBuffer();
	     int lenFlag = s.indexOf("|");
	     if(lenFlag<0 || lenFlag>=s.length())return s;
	     int len = Integer.parseInt(s.substring(0,lenFlag));
	     s = s.substring(lenFlag+1);
	     byte b[] = new byte[len];
	     int index = 0;
	     for(int i = 0; i < s.length (); i++) {
		 char c = s.charAt(i);
		 if(c != '*') {
		     strBuf.append(c);
		 }else{
		     b[index] = (byte) (Integer.parseInt (strBuf.toString ()));
		     strBuf.delete(0,strBuf.length());
		     index++;
		 }
	     }
	    try {
		return new String (b, "UTF-8");
	    }
	    catch(UnsupportedEncodingException ex) {
		return null;
	    }
	 }
	 public static String encode(String s) {
	  int len = 0;
	  boolean wroteUnencodedChar = false;

	  StringBuffer writer = new StringBuffer();

	  StringBuffer out = new StringBuffer(s.length());

	  for (int i = 0; i < s.length(); i++) {
	   char c = s.charAt(i);
	    try {
	     if (wroteUnencodedChar) {
	      writer = new StringBuffer();
	      wroteUnencodedChar = false;
	     }

	     writer.append(c);

	     if (c >= 0xD800 && c <= 0xDBFF) {
	      if ((i + 1) < s.length()) {
	       int d = (int) (s.charAt(i + 1));

	       if (d >= 0xDC00 && d <= 0xDFFF) {
		writer.append(d);
		i++;
	       }
	      }
	     }

	    } catch (Exception e) {
	     writer = new StringBuffer();
	     continue;
	    }

	    String str = writer.toString();

	    ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    DataOutputStream dos = new DataOutputStream(baos);
	    try {
	     dos.writeUTF(str);
	     dos.flush();
	    } catch (Exception e) {
	     e.printStackTrace();
	    }

	    byte[] temp = baos.toByteArray();

	    byte[] ba = new byte[temp.length - 2];
	    for (int ix = 0; ix < ba.length; ix++) {
	     ba[ix] = temp[ix + 2];
	    }

	    for (int j = 0; j < ba.length; j++) {
		out.append(ba[j]);
	     out.append('*');
	     len++;
	    }
	    writer = new StringBuffer();
	    try {
	     dos.close();
	     baos.close();
	    } catch (Exception e) {
	     e.printStackTrace();
	    }
	//   }
	  }

	  return len+"|"+out.toString();
	 }
	 /** 瀛楃涓查粯璁ら敭鍊?    */
	 private static String strDefaultKey = "national";

	 /** 鍔犲瘑宸ュ叿     */
	 private static Cipher encryptCipher = null;

	 /** 瑙e瘑宸ュ叿     */
	 private static Cipher decryptCipher = null;

	 /**  
	  * 灏哹yte鏁扮粍杞崲涓鸿〃绀?6杩涘埗鍊肩殑瀛楃涓诧紝 濡傦細byte[]{8,18}杞崲涓猴細0813锛?鍜宲ublic static byte[]  
	  * hexStr2ByteArr(String strIn) 浜掍负鍙€嗙殑杞崲杩囩▼  
	  *   
	  * @param arrB  
	  *            闇€瑕佽浆鎹㈢殑byte鏁扮粍  
	  * @return 杞崲鍚庣殑瀛楃涓? 
	  * @throws Exception  
	  *             鏈柟娉曚笉澶勭悊浠讳綍寮傚父锛屾墍鏈夊紓甯稿叏閮ㄦ姏鍑? 
	  */
	 public static String byteArr2HexStr(byte[] arrB) throws Exception {
	   int iLen = arrB.length;
	   // 姣忎釜byte鐢ㄤ袱涓瓧绗︽墠鑳借〃绀猴紝鎵€浠ュ瓧绗︿覆鐨勯暱搴︽槸鏁扮粍闀垮害鐨勪袱鍊?  
	   StringBuffer sb = new StringBuffer(iLen * 2);
	   for (int i = 0; i < iLen; i++) {
	     int intTmp = arrB[i];
	     // 鎶婅礋鏁拌浆鎹负姝f暟   
	     while (intTmp < 0) {
	       intTmp = intTmp + 256;
	     }
	     // 灏忎簬0F鐨勬暟闇€瑕佸湪鍓嶉潰琛?   
	     if (intTmp < 16) {
	       sb.append("0");
	     }
	     sb.append(Integer.toString(intTmp, 16));
	   }
	   return sb.toString();
	 }

	 /**  
	  * 灏嗚〃绀?6杩涘埗鍊肩殑瀛楃涓茶浆鎹负byte鏁扮粍锛?鍜宲ublic static String byteArr2HexStr(byte[] arrB)  
	  * 浜掍负鍙€嗙殑杞崲杩囩▼  
	  *   
	  * @param strIn  
	  *            闇€瑕佽浆鎹㈢殑瀛楃涓? 
	  * @return 杞崲鍚庣殑byte鏁扮粍  
	  * @throws Exception  
	  *             鏈柟娉曚笉澶勭悊浠讳綍寮傚父锛屾墍鏈夊紓甯稿叏閮ㄦ姏鍑? 
	  * @author <a href="mailto:leo841001@163.com">LiGuoQing</a>  
	  */
	 public static byte[] hexStr2ByteArr(String strIn) throws Exception {
	   byte[] arrB = strIn.getBytes();
	   int iLen = arrB.length;

	   // 涓や釜瀛楃琛ㄧず涓€涓瓧鑺傦紝鎵€浠ュ瓧鑺傛暟缁勯暱搴︽槸瀛楃涓查暱搴﹂櫎浠?   
	   byte[] arrOut = new byte[iLen / 2];
	   for (int i = 0; i < iLen; i = i + 2) {
	     String strTmp = new String(arrB, i, 2);
	     arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
	   }
	   return arrOut;
	 }


	 /**  
	  * 鎸囧畾瀵嗛挜鏋勯€犳柟娉? 
	  *   
	  * @param strKey  
	  *            鎸囧畾鐨勫瘑閽? 
	  * @throws Exception  
	  */
	 static String strKey = "zjlinegame";
	 static boolean noInit = true;
	 public static void init() throws Exception {

	   Key key = getKey(strKey.getBytes());

	   encryptCipher = Cipher.getInstance("DES");
	   encryptCipher.init(Cipher.ENCRYPT_MODE, key);

	   decryptCipher = Cipher.getInstance("DES");
	   decryptCipher.init(Cipher.DECRYPT_MODE, key);
	 }

	 /**  
	  * 鍔犲瘑瀛楄妭鏁扮粍  
	  *   
	  * @param arrB  
	  *            闇€鍔犲瘑鐨勫瓧鑺傛暟缁? 
	  * @return 鍔犲瘑鍚庣殑瀛楄妭鏁扮粍  
	  * @throws Exception  
	  */
		public static byte[] encrypt(byte[] arrB) {
			byte data[] = null;
			try {
				data = encryptCipher.doFinal(arrB);
			} catch (IllegalBlockSizeException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (BadPaddingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return data;
		}

	 /**  
	  * 鍔犲瘑瀛楃涓? 
	  *   
	  * @param strIn  
	  *            闇€鍔犲瘑鐨勫瓧绗︿覆  
	  * @return 鍔犲瘑鍚庣殑瀛楃涓? 
	  * @throws Exception  
	  */
		public static String encrypt(String strIn) {
			if(noInit)
			{
				noInit = false;
				try {
					init();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			String res = "";
			try {
				res = byteArr2HexStr(encrypt(strIn.getBytes()));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return res;
		}

	 /**  
	  * 瑙e瘑瀛楄妭鏁扮粍  
	  *   
	  * @param arrB  
	  *            闇€瑙e瘑鐨勫瓧鑺傛暟缁? 
	  * @return 瑙e瘑鍚庣殑瀛楄妭鏁扮粍  
	  * @throws Exception  
	  */
	 public static byte[] decrypt(byte[] arrB) throws Exception {
	   return decryptCipher.doFinal(arrB);
	 }

	 /**  
	  * 瑙e瘑瀛楃涓? 
	  *   
	  * @param strIn  
	  *            闇€瑙e瘑鐨勫瓧绗︿覆  
	  * @return 瑙e瘑鍚庣殑瀛楃涓? 
	  * @throws Exception  
	  */
	 public static String decrypt(String strIn) throws Exception {
		if (noInit) {
			noInit = false;
			try {
				init();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	   return new String(decrypt(hexStr2ByteArr(strIn)),"UTF-8");
	 }

	 /**  
	  * 浠庢寚瀹氬瓧绗︿覆鐢熸垚瀵嗛挜锛屽瘑閽ユ墍闇€鐨勫瓧鑺傛暟缁勯暱搴︿负8浣?涓嶈冻8浣嶆椂鍚庨潰琛?锛岃秴鍑?浣嶅彧鍙栧墠8浣? 
	  *   
	  * @param arrBTmp  
	  *            鏋勬垚璇ュ瓧绗︿覆鐨勫瓧鑺傛暟缁? 
	  * @return 鐢熸垚鐨勫瘑閽? 
	  * @throws java.lang.Exception  
	  */
	 private static Key getKey(byte[] arrBTmp) throws Exception {
	   // 鍒涘缓涓€涓┖鐨?浣嶅瓧鑺傛暟缁勶紙榛樿鍊间负0锛?  
	   byte[] arrB = new byte[8];

	   // 灏嗗師濮嬪瓧鑺傛暟缁勮浆鎹负8浣?  
	   for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
	     arrB[i] = arrBTmp[i];
	   }

	   // 鐢熸垚瀵嗛挜   
	   Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");

	   return key;
	 }
	}