Java中的base64编码与解码

直接上程序:
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.UnsupportedEncodingException;

//base64加密
  public  String EncodeBase64(String str){
        byte[] b=null;
        String s=null;
        try {
            b = str.getBytes(this.Charset);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if(b!=null){
            s=new BASE64Encoder().encode(b);
            System.out.println("加密:"+s);
        }
        return s;
    }
//base64解密  
  public  String DecodeBase64(String s) {  
      byte[] b = null;  
      String result = null;  
      if (s != null) {  
          BASE64Decoder decoder = new BASE64Decoder();  
          try {  
              b = decoder.decodeBuffer(s);  
              result = new String(b, this.Charset);  
              System.out.println("解密:"+result);
          } catch (Exception e) {  
              e.printStackTrace();  
          }  
      }  
      return result;  

  } 

注意:在eclipse编译器会报错,进行设置:windows->preferences->Java->Compiler->Errors/Warnings->Deprecated and retricted API ->将下面的三项都设置为Warning

经测试,可行。



你可能感兴趣的:(Java中的base64编码与解码)