使用JDK的類 BASE64Decoder BASE64Encoder Java代碼 package test; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; /** * BASE64加密解密 */ public clas
使用JDK的類 BASE64Decoder BASE64Encoder
Java代碼
- package test;
- import sun.misc.BASE64Decoder;
- import sun.misc.BASE64Encoder;
- /**
- * BASE64加密解密
- */
- public class BASE64
- {
- /**
- * BASE64解密
- * @param key
- * @return
- * @throws Exception
- */
- public static byte[] decryptBASE64(String key) throws Exception {
- return (new BASE64Decoder()).decodeBuffer(key);
- }
- /**
- * BASE64加密
- * @param key
- * @return
- * @throws Exception
- */
- public static String encryptBASE64(byte[] key) throws Exception {
- return (new BASE64Encoder()).encodeBuffer(key);
- }
- public static void main(String[] args) throws Exception
- {
- String para = "{\"IdList1\": 1,\"IdList2\": [1,2,3,4,5,6,18],\"IdList3\": [1,2]}";
- String data = BASE64.encryptBASE64(para.getBytes());
- System.out.println("加密前:"+data);
- byte[] byteArray = BASE64.decryptBASE64(data);
- System.out.println("解密後:"+new String(byteArray));
- }
- }
使用Apache commons codec 類Base64獲取【下載地址】
Java代碼
- package test;
- import java.io.UnsupportedEncodingException;
- import org.apache.commons.codec.binary.Base64;
- public class Base64Util {
- public static String encode(byte[] binaryData) throws UnsupportedEncodingException {
- return new String(Base64.encodeBase64(binaryData), "UTF-8");
- }
- public static byte[] decode(String base64String) throws UnsupportedEncodingException {
- return Base64.decodeBase64(base64String.getBytes("UTF-8"));
- }
- public static void main(String[] args) throws UnsupportedEncodingException {
- String para = "{\"IdList1\": 1,\"IdList2\": [1,2,3,4,5,6,18],\"IdList3\": [1,2]}";
- String data = Base64Util.encode(para.getBytes());
- System.out.println("加密前:"+data);
- byte[] byteArray = Base64Util.decode(data);
- System.out.println("解密後:"+new String(byteArray));
- }
- }