早期作法
早期在Java上做Base64的编码与解码,会使用到JDK里sun.misc套件下的BASE64Encoder和BASE64Decoder这两个类别,用法如下:
private static void beforeJDK1_8() throws IOException { BASE64Encoder encoder = new BASE64Encoder(); BASE64Decoder decoder = new BASE64Decoder(); String text = "你好么?"; byte[] bytesText = text.getBytes("UTF-8"); String encodeString = encoder.encode(bytesText); System.out.println("编码: " + encodeString); byte[] bytesDeText = decoder.decodeBuffer(encodeString); System.out.println(new String(bytesDeText,"UTF-8")); }
Apache Commons Codec作法
public static String base64Encode(String data){ return Base64.encodeBase64String(data.getBytes()); } public static byte[] base64Decode(String data){ return Base64.decodeBase64(data.getBytes()); } public static String md5(String data) { return DigestUtils.md5Hex(data); } public static String sha1(String data) { return DigestUtils.shaHex(data); } public static String sha256Hex(String data) { return DigestUtils.sha256Hex(data); }
private static void ApacheUtils() throws UnsupportedEncodingException { String base64 = base64Encode("ricky"); System.out.println("base64 encode="+base64); byte[] buf = base64Decode(base64); System.out.println("base64 decode="+new String(buf)); String md5 = md5("ricky"); System.out.println("md5="+md5+"**len="+md5.length()); String sha1 = sha1("test"); System.out.println("sha1="+sha1+"**len="+sha1.length()); }
Java 8之后的作法
Java 8的java.util套件中,新增了Base64的类别,可以用来处理Base64的编码与解码,用法如下:
private static void afterJDK1_8() throws UnsupportedEncodingException { Base64.Encoder encoder = Base64.getEncoder(); Base64.Decoder decoder = Base64.getDecoder(); String text = "你妹的!"; byte[] bytesEnText = text.getBytes("UTF-8"); String encodeToString = encoder.encodeToString(bytesEnText); System.out.println(encodeToString); byte[] byteDeText = decoder.decode(encodeToString); System.out.println(new String(byteDeText,"UTF-8")); }