Java Base64 加密解密

本文介绍了使用Java JDK内置的BASE64Decoder和BASE64Encoder类进行数据加密和解密,并通过Apache Commons Codec库的Base64类展示了另一种实现方式。通过实例代码演示了加密前后的数据变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用JDK的类 BASE64Decoder  BASE64Encoder

 

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

 

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));  
    }


}