Base64Util.java
package com.zby.util;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;public class Base64Util { private static final BASE64Encoder ENCODER = new BASE64Encoder(); private static final BASE64Decoder DECODER = new BASE64Decoder(); private Base64Util() { throw new RuntimeException("NO!"); } public static String encode(byte[] data) { return ENCODER.encodeBuffer(data); } public static byte[] decode(String data) throws Exception { return DECODER.decodeBuffer(data); } public static String encodeFromString(String data) { return encode(data.getBytes()); } public static String decodeToString(String data) throws Exception { return new String(decode(data)); }}
TestBase64.java
package com.zby;import com.zby.util.Base64Util;public class TestBase64 { public static void main(String[] args) throws Exception { String data = "Hello,World!"; System.out.println("源字符串:" + data); String encoded = Base64Util.encodeFromString(data); System.out.println("Base64加密后字符串:" + encoded); String decoded = Base64Util.decodeToString(encoded); System.out.println("Base64解密后字符串:" + decoded); }}
控制台输出:
源字符串:Hello,World!Base64加密后字符串:SGVsbG8sV29ybGQhBase64解密后字符串:Hello,World!