1 package cn.home1.oss.lib.common;
2
3 import static org.apache.commons.codec.CharEncoding.UTF_8;
4
5 import lombok.SneakyThrows;
6
7 import org.apache.commons.codec.net.URLCodec;
8
9 /**
10 * Created by zhanghaolun on 16/11/16.
11 */
12 public abstract class CodecUtils {
13
14 private CodecUtils() {
15 }
16
17 /**
18 * other ways to do this.
19 * <pre>
20 * {@code
21 * new org.apache.commons.codec.binary.Base64().encode,encodeToString
22 * io.jsonwebtoken.impl.TextCodec.BASE64.encode
23 * com.fasterxml.jackson.core.Base64Variants.MIME_NO_LINEFEEDS.encode()
24 * new String(org.apache.commons.codec.binary.Base64.encodeBase64(raw, UTF_8)
25 * }
26 * </pre>
27 *
28 * @param raw raw bytes
29 * @return base64 string
30 */
31 public static String encodeBase64(final byte[] raw) {
32 return java.util.Base64.getEncoder().encodeToString(raw);
33 }
34
35 /**
36 * other ways to do this.
37 * <pre>
38 * {@code
39 * org.springframework.security.crypto.codec.Base64.decode(base64String.getBytes(UTF_8.name()));
40 * new sun.misc.BASE64Decoder().decodeBuffer(base64String);
41 * org.apache.commons.codec.binary.Base64.decodeBase64(base64String);
42 * }
43 * </pre>
44 *
45 * @param base64String base64 string
46 * @return raw bytes
47 */
48 @SneakyThrows
49 public static byte[] decodeBase64(final String base64String) {
50 return java.util.Base64.getDecoder().decode(base64String);
51 }
52
53 private static final URLCodec URL_CODEC = new URLCodec(UTF_8);
54
55 /**
56 * other ways to do this.
57 * <pre>
58 * {@code
59 * java.net.URLEncoder.encode(text, UTF_8.name())
60 * }
61 * </pre>
62 *
63 * @param text text to encode
64 * @return encoded text
65 */
66 @SneakyThrows
67 public static String urlEncode(final String text) {
68 return text != null ? URL_CODEC.encode(text) : null;
69 }
70
71 @SneakyThrows
72 public static String urlDecode(final String text) {
73 return text != null ? URL_CODEC.decode(text) : null;
74 }
75 }