BASE64 and other similar encoding algorithms are commonly used to convert binary data into text data, with the purpose of simplifying storage or transmission. More specifically, the BASE64 algorithm is mainly used to convert binary data into ASCII string format. Java language provides a very good implementation of BASE64 algorithm. This article will briefly describe how to use BASE64 and how it works.
The function of Base64: Its main purpose is not encryption, its main purpose is to convert some binary numbers into ordinary characters for network transmission. Since some binary characters are control characters in the transmission protocol, they cannot be directly transmitted and need to be converted.
The first method:
Use classes in Java that are not exposed to the public through reflection:
/*** * encode by Base64 */ public static String encodeBase64(byte[]input) throws Exception{ Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64"); Method mainMethod= clazz.getMethod("encode", byte[].class); mainMethod.setAccessible(true); Object retObj=mainMethod.invoke(null, new Object[]{input}); return (String)retObj; } /*** * decode by Base64 */ public static byte[] decodeBase64(String input) throws Exception{ Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64"); Method mainMethod= clazz.getMethod("decode", String.class); mainMethod.setAccessible(true); Object retObj=mainMethod.invoke(null, input); return (byte[])retObj; } The second method:
Use commons-codec.jar
/** * @param bytes * @return */ public static byte[] decode(final byte[] bytes) { return Base64.decodeBase64(bytes); } /** * Binary data is encoded as BASE64 string* * @param bytes * @return * @throws Exception */ public static String encode(final byte[] bytes) { return new String(Base64.encodeBase64(bytes)); } The third method:
/** * Encoding* @param bstr * @return String */ public static String encode(byte[] bstr){ return new sun.misc.BASE64Encoder().encode(bstr); } /** * Decoding* @param str * @return string */ public static byte[] decode(String str){ byte[] bt = null; try { sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder(); bt = decoder.decodeBuffer( str ); } catch (IOException e) { e.printStackTrace(); } return bt; }The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.