Java Base64 编码/解码
基于 java.util.Base64(java8以上)
package pink.isky.cactus.utils; import java.io.UnsupportedEncodingException; import java.util.Base64; /** * @Author * @Date 2020/5/21 9:46 */ public class Base64Util { public static String encodeStr(String str) { Base64.Encoder encoder = Base64.getEncoder(); byte[] textByte; String encodedText = null; try { textByte = str.getBytes("UTF-8"); encodedText = encoder.encodeToString(textByte); return encodedText; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return encodedText; } public static String decodeStr(String encodedStr) { Base64.Decoder decoder = Base64.getDecoder(); byte[] textBytes = decoder.decode(encodedStr); String decodedStr = null; try { decodedStr = new String(textBytes,"UTF-8"); return decodedStr; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return decodedStr; } }
基于 org.apache.commons.codec.binary.Base64;
package pink.isky.cactus.utils; import org.apache.commons.codec.binary.Base64; import java.io.UnsupportedEncodingException; /** * @Author * @Date 2020/5/21 10:05 */ public class CodeUtil { public static String encodeText(String text) { Base64 base64 = new Base64(); String encodedText = null; try { byte[] textByte = text.getBytes("UTF-8"); encodedText = base64.encodeToString(textByte); return encodedText; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return encodedText; } public static String decodeText(String encodedText) { final Base64 base64 = new Base64(); byte[] textByte = base64.decode(encodedText); String decodedText = null; try { decodedText = new String(textByte,"UTf-8"); return decodedText; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return decodedText; } }