欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java Base64 加密解密

程序员文章站 2022-06-30 22:58:53
...

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


}