幾個月之前,打算寫個簡單的加密用於項目,總算騰出點時間。在處理第一步字符串轉二進制並反轉時,以為有簡單現成的,結果國內看了看都不太好使(沒找到),8位和16位同時處理總有點bug。前一天弄了幾個小時沒弄好,先干工其他的了。今早,感覺可以,一小會就搞定了,分開處理一下就好了。有需要做相關處理的,供參考。廢話不多說了,直接上代碼:
1 import java.io.UnsupportedEncodingException; 2 3 public class EncryptionPrepare { 4 /* 5 * 轉為二進制 6 */ 7 public static String toBinary(String str,String split){ 8 9 char[] strChar=str.toCharArray(); 10 StringBuffer tempStr=new StringBuffer(); 11 int length=strChar.length; 12 for(int i=0;i<length;i++){ 13 tempStr.append(Integer.toBinaryString(strChar[i])); 14 tempStr.append(split); 15 } 16 return tempStr.toString(); 17 } 18 /* 19 * 轉成中英文 20 */ 21 public static String toNormalStr(String str){ 22 byte[] bs = new byte[str.length() / 2]; 23 int len = bs.length; 24 if (len == 1) { 25 bs[0] = (byte) Integer.parseInt(str.substring(0, 2), 16); 26 try { 27 return new String(bs, "utf-8"); 28 } catch (UnsupportedEncodingException e) { 29 e.printStackTrace(); 30 } 31 }else if (len == 2) { 32 for (int i = 0; i < len; i++) { 33 bs[i] = (byte) Integer.parseInt( 34 str.substring(i<<1, (i<<1) + 2), 16);
35 } 36 try { 37 return new String(bs, "utf-16"); 38 } catch (UnsupportedEncodingException e) { 39 e.printStackTrace(); 40 } 41 } 42 return "wrong"; 43 44 } 45 /* 46 * 獲取中英文 47 */ 48 public static String getNormalStr(String str,String split){ 49 String[] tempStr = StrToStrArray(str,split); 50 StringBuffer strBuffer=new StringBuffer(); 51 int len=tempStr.length; 52 for (int i = 0; i < len; i++) { 53 strBuffer.append(toNormalStr(Integer.toHexString(Integer.parseInt(tempStr[i], 2)))); 54 } 55 return strBuffer.toString(); 56 57 } 58 /* 59 * 以不同字符分割 60 */ 61 private static String[] StrToStrArray(String str,String split) { 62 return str.split(split); 63 } 64 //測試 65 public static void main(String[] args) throws UnsupportedEncodingException { 66 System.out.println(EncryptionPrepare.toBinary("1網this測試一下jk%"," ")); 67 System.out.println(EncryptionPrepare.getNormalStr("110001 111111101010001 1110100 1101000 1101001 1110011 110110101001011 1000101111010101 100111000000000 100111000001011 1101010 1101011 100101"," ")); 68 69 } 70 }