java字符串加密解密

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 

posted @ 2018-07-13 09:49  何其小静  阅读(11045)  评论(0编辑  收藏  举报