Base64编码
| 10 | * |
| 11 | */ |
| 12 | public class Base64 { |
| 13 | private static final Logger logger = LogManager.getLogger(Base64.class); |
| 14 | /** |
| 15 | * 安全的Base64编码(将Base64中的URL非法字符如+,/=转为其他字符, 见RFC3548). |
| 16 | * @param data 数据 |
| 17 | * @return |
| 18 | */ |
| 19 | public static String encodeBase64URL(String data){ |
| 20 | if(data != null && !data.isEmpty()){ |
| 21 | return org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(data.getBytes(StandardCharsets.UTF_8 )); |
| 22 | } |
| 23 | return ""; |
| 24 | } |
| 25 | |
| 26 | /** |
| 27 | * 安全的Base64解码 |
| 28 | * @param data 数据 |
| 29 | * @return |
| 30 | */ |
| 31 | public static String decodeBase64URL(String data){ |
| 32 | if(data != null && !data.isEmpty()){ |
| 33 | return new String(org.apache.commons.codec.binary.Base64.decodeBase64(data),StandardCharsets.UTF_8); |
| 34 | } |
| 35 | return ""; |
| 36 | } |
| 37 | |
| 38 | |
| 39 | |
| 40 | private static final char[] base64EncodeChars = new char[]{ |
| 41 | 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', |
| 42 | 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', |
| 43 | 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', |
| 44 | 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', |
| 45 | 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', |
| 46 | 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', |
| 47 | 'w', 'x', 'y', 'z', '0', '1', '2', '3', |
| 48 | '4', '5', '6', '7', '8', '9', '+', '/'}; |
| 49 | private static final byte[] base64DecodeChars = new byte[]{ |
| 50 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
| 51 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
| 52 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, |
| 53 | 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, |
| 54 | -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, |
| 55 | 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, |
| 56 | -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, |
| 57 | 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1}; |
| 58 | |
| 59 | public static String encode(byte[] data) { |
| 60 | StringBuffer sb = new StringBuffer(); |
| 61 | int len = data.length; |
| 62 | int i = 0; |
| 63 | int b1, b2, b3; |
| 64 | while (i < len) { |
| 65 | b1 = data[i++] & 0xff; |
| 66 | if (i == len) { |
| 67 | sb.append(base64EncodeChars[b1 >>> 2]); |
| 68 | sb.append(base64EncodeChars[(b1 & 0x3) << 4]); |
| 69 | sb.append("=="); |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…