Java implements BASE64 encoding and decoding methods

  • 2020-05-16 06:59:42
  • OfStack

BASE64 and other similar encoding algorithms are commonly used to convert binary data into text data in order to simplify storage or transmission. More specifically, the BASE64 algorithm is primarily used to convert base 2 data into ASCII string format. The Java language provides a very good implementation of the BASE64 algorithm. This article will briefly describe how to use BASE64 and how it works.

What Base64 does: it is not primarily encrypted. Its main purpose is to convert base 1 Numbers into normal characters for network transmission. Since some base 2 characters belong to the control characters in the transport protocol, it is not possible to transfer them directly.

Method 1:
Using java's private classes through reflection:


/*** 
   * encode by Base64 
   */ 
  public static String encodeBase64(byte[]input) throws Exception{ 
    Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64"); 
    Method mainMethod= clazz.getMethod("encode", byte[].class); 
    mainMethod.setAccessible(true); 
     Object retObj=mainMethod.invoke(null, new Object[]{input}); 
     return (String)retObj; 
  } 
  /*** 
   * decode by Base64 
   */ 
  public static byte[] decodeBase64(String input) throws Exception{ 
    Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64"); 
    Method mainMethod= clazz.getMethod("decode", String.class); 
    mainMethod.setAccessible(true); 
     Object retObj=mainMethod.invoke(null, input); 
     return (byte[])retObj; 
  } 

The second way:

Use the commons - codec jar


/** 
   * @param bytes 
   * @return 
   */ 
  public static byte[] decode(final byte[] bytes) { 
    return Base64.decodeBase64(bytes); 
  } 
 
  /** 
   * 2 The base data is encoded as BASE64 string  
   * 
   * @param bytes 
   * @return 
   * @throws Exception 
   */ 
  public static String encode(final byte[] bytes) { 
    return new String(Base64.encodeBase64(bytes)); 
  } 

The third way:


/** 
  *  coding  
  * @param bstr 
  * @return String 
  */  
  public static String encode(byte[] bstr){  
  return new sun.misc.BASE64Encoder().encode(bstr);  
  }  
  
  /** 
  *  decoding  
  * @param str 
  * @return string 
  */  
  public static byte[] decode(String str){  
  byte[] bt = null;  
  try {  
    sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();  
    bt = decoder.decodeBuffer( str );  
  } catch (IOException e) {  
    e.printStackTrace();  
  }  
  
    return bt;  
  }  

Related articles: