LALA |
|
|||
日歷
導航留言簿(1)隨筆分類(31)
文章分類(4)收藏夾(21)搜索積分與排名
最新隨筆
最新評論
閱讀排行榜 |
Google Base64可以搜到相關原理和許多實現。
下面是我的實現,和SUN公司提供的參考實現。 1 public class Base64 {
2 static String base64_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; 3 4 /** 5 * 編碼原理:將3個字節轉換成4個字節( (3 X 8) = 24 = (4 X 6) ) 6 * 先讀入3個字節,每讀一個字節,左移8位,再右移四次,每次6位,這樣就有4個字節了 7 * 8 * @param data 9 * @return 編碼后的Base64字符串 10 */ 11 public static String Base64Encode(byte[] data) { 12 StringBuilder builder = new StringBuilder(); 13 int[] temp = new int[4]; 14 int len = data.length - data.length % 3; 15 for (int i = 0; i < len; i += 3) { 16 int goal = 0; 17 for (int j = 0; j < 3; j++) { 18 goal <<= 8; 19 goal |= (data[i + j] & 0xff); 20 } 21 for (int k = 0; k < 4; k++) { 22 temp[k] = goal & 0x3f; 23 goal >>= 6; 24 } 25 for (int k = 3; k >= 0; k--) { 26 builder.append(base64_alphabet.charAt(temp[k])); 27 } 28 } 29 int index; 30 switch (data.length % 3) { 31 case 1: 32 index = data[data.length - 1] >> 2; 33 builder.append(base64_alphabet.charAt(index)); 34 index = (data[data.length - 1] & 0x03) << 4; 35 builder.append(base64_alphabet.charAt(index)); 36 builder.append("=="); 37 break; 38 case 2: 39 index = data[data.length - 1 - 1] >> 2; 40 builder.append(base64_alphabet.charAt(index)); 41 index = (data[data.length - 1 - 1] & 0x03) << 4 42 | data[data.length - 1] >> 4; 43 builder.append(base64_alphabet.charAt(index)); 44 index = (data[data.length - 1] & 0x0f) << 2; 45 builder.append(base64_alphabet.charAt(index)); 46 builder.append('='); 47 break; 48 } 49 return builder.toString(); 50 } 51 52 /** 53 * 解碼原理:將4個字節轉換成3個字節. 先讀入4個6位(用或運算),每次左移6位,再右移3次,每次8位. 54 * 55 * @param data 56 * 需解碼的Base64字符串。 57 * @return byte[]-解碼出的字節數組 58 */ 59 public static byte[] Base64Decode(String data) { 60 char[] chArray = data.toCharArray(); 61 int len = chArray.length; 62 byte[] result = new byte[len * 3 / 4]; 63 for (int i = 0, res_i = 0; i < len; i += 4, res_i += 3) { 64 int goal = 0; 65 int index = 0; 66 for (int k = 0; k < 4; k++) { 67 index = base64_alphabet.indexOf(chArray[i + k]); 68 goal <<= 6; 69 goal |= index; 70 } 71 for (int j = 2; j >= 0; j--) { 72 result[res_i + j] = (byte) goal; 73 goal >>= 8; 74 } 75 } 76 // 等號=的處理 77 if (chArray[len - 1] != '=') 78 return result; 79 else if (chArray[len - 2] == '=') 80 return Arrays.copyOf(result, result.length - 2); 81 else 82 return Arrays.copyOf(result, result.length - 1); 83 84 } 85 // 將 s 進行 BASE64 編碼 86 public static String getBASE64(String s) { 87 if (s == null) 88 return null; 89 return (new sun.misc.BASE64Encoder()).encode(s.getBytes()); 90 } 91 92 // 將 BASE64 編碼的字符串 s 進行解碼 93 public static String getFromBASE64(String s) { 94 if (s == null) 95 return null; 96 BASE64Decoder decoder = new BASE64Decoder(); 97 try { 98 byte[] b = decoder.decodeBuffer(s); 99 return new String(b); 100 } catch (Exception e) { 101 return null; 102 } 103 } 104 } |
![]() |
|
Copyright © Dest | Powered by: 博客園 模板提供:滬江博客 |