java字符串加密解密
字符串加密解密的方式很多,每一種加密有着相對的解密方法。下面要說的是java中模擬php的pack和unpack的字符串加密解密方法。
java模擬php中pack:
1 /** 2 * 十六進制轉中文字符串 3 */ 4 public static String decodeString(String str) { 5 if ( str == null ) { 6 return "轉換失敗"; 7 } 8 byte[] s = pack(str); //十六進制轉byte數組 9 String gbk; 10 try { 11 gbk = new String(s, "gbk"); //byte數組轉中文字符串 12 } catch ( UnsupportedEncodingException ignored ) { 13 gbk = "轉換失敗"; 14 } 15 return gbk; 16 }
1 /** 2 * 十六進制轉byte數組,模擬php中pack 3 */ 4 public static byte[] pack(String str) { 5 int nibbleshift = 4; 6 int position = 0; 7 int len = str.length() / 2 + str.length() % 2; 8 byte[] output = new byte[len]; 9 for (char v : str.toCharArray()) { 10 byte n = (byte) v; 11 if (n >= '0' && n <= '9') { 12 n -= '0'; 13 } else if (n >= 'A' && n <= 'F') { 14 n -= ('A' - 10); 15 } else if (n >= 'a' && n <= 'f') { 16 n -= ('a' - 10); 17 } else { 18 continue; 19 } 20 output[position] |= (n << nibbleshift); 21 if (nibbleshift == 0) { 22 position++; 23 } 24 nibbleshift = (nibbleshift + 4) & 7; 25 } 26 return output; 27 }
java模擬php中unpack:
1 /** 2 * 中文字符串轉十六進制 3 */ 4 public static String decodeShiLiu(String str) { 5 if ( str == null ) { 6 return "轉換失敗"; 7 } 8 String gbk; 9 try { 10 byte[] sss = str.getBytes("GBK"); //中文字符串轉byte數組 11 gbk = unpack(sss); // byte數組轉十六進制 12 } catch ( Exception E ) { 13 gbk = "轉換失敗"; 14 } 15 return gbk; 16 }
1 /** 2 * byte數組轉十六進制,模擬php中unpack 3 */ 4 public static String unpack(byte[] bytes) { 5 StringBuilder stringBuilder = new StringBuilder(""); 6 if (bytes == null || bytes.length <= 0) { 7 return null; 8 } 9 for (int i = 0; i < bytes.length; i++) { 10 int v = bytes[i] & 0xFF; 11 String hv = Integer.toHexString(v); 12 if (hv.length() < 2) { 13 stringBuilder.append(0); 14 } 15 stringBuilder.append(hv); 16 } 17 return stringBuilder.toString(); 18 }
對其進行實例:
1 public static void main(String[] args) throws ParseException{ 2 3 System.out.println(decodeString("b2a9bfcdd4b0d6d0cec4")); 4 System.out.println(decodeShiLiu("博客園中文")); 5 }
輸出結果:
博客園中文
b2a9bfcdd4b0d6d0cec4