BASE64 and other similar coding algorithms are commonly used to convert binary data to text data, which is intended to simplify storage or transmission. More specifically, the BASE64 algorithm is primarily used to convert binary data into ASCII string format. The Java language provides a very good implementation of the BASE64 algorithm. This article will briefly describe how to use BASE64 and how it works.
The role of BASE64: mainly not encryption, its main purpose is to convert some binary numbers into ordinary characters for network transmission. Since some binary characters belong to the control character in the transmission protocol, it is not possible to transfer the data directly.
The first way:
To use a class that is not exposed in Java by 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 way:
Using Commons-codec.jar
/**
* @param bytes
* @return
/public static byte[] Decode (final byte[] bytes) {
return Base64.decodebase64 (bytes);
}
/**
* Binary data encoded as BASE64 string
*
* @param bytes *
@return *
@throws Exception
/Public Static String encode (final byte[] bytes) {return
new String (base64.encodebase64 (bytes));
}
The Third Way:
/** *
Code
* @param BSTR
* @return string
/public static string encode (Byte[] BSTR) {return
new S Un.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 the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.