Base64加密解密工具

package cn.demo.file;
public class Test0 {
   private static char[] base64Code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
   private static int[] toInt = new int[128];

   //存储的是与base64编码对应的索引
   static {
       for (int i = 0; i < base64Code.length; i++) {
           toInt[base64Code[i]] = i;
       }
   }

  //主函数
   public static void main(String[] args) {
      /* String str  = "0123456789bcdef";
       String str2 = toBase64(str.getBytes());
       System.out.println(str2);*/
       String str  = "123456";
       String str2 = toBase64(str.getBytes());
       System.out.println(str2);
       
       System.out.println(deBase64(str2));
   }
   //Base64编码
   public  static String toBase64(byte[] byteArr){
       //判空
       if(byteArr == null || byteArr.length == 0){
           return  null;
       }
       //确定字符数组的长度
       char[] chars = new char[(byteArr.length + 2) / 3 * 4];
       int i = 0;
       int count = 0;
       while(i < byteArr.length){
           //获取原始数据的ascii码值
           byte b0 = byteArr[i++];
           byte b1 = (i < byteArr.length) ? byteArr[i++] : 0;
           byte b2 = (i < byteArr.length) ? byteArr[i++] : 0;

           //转化为对应的base数
           /**
            * 这是3位转4位
            * 第一位 右移两位高位补0没问题
            * 第二位 b0左移到高4位低四位补0  b1 右移到低四位  结合就是b0原本的低四位 + b1的高四位
            * 这里会有问题? 我们只要b0的最后两位和b1的高四位, b0左移4位高2位不一定会是00
            * “& 0x3f ”的作用就是保证高2位是00
            * 第三位第四位同理
            * */
           chars[count++] = base64Code[(b0 >> 2) & 0x3f];
           chars[count++] = base64Code[((b0 << 4) | (b1 >> 4)) & 0x3f];
           chars[count++] = base64Code[((b1 << 2) | (b2 >> 6)) & 0x3f];
           chars[count++] = base64Code[b2 & 0x3f];
       }
       //添加'='  case渗透
       switch (byteArr.length % 3){
           case 1 : chars[--count] = '=';
           case 2 : chars[--count] = '=';
       }
       return new String(chars);
   }

   //Base64解码
   public  static String deBase64(String str){
    //先判空
    if(str == null || str.length() == 0){
        return  str;
    }
    int tempNum  = str.endsWith("==") ? 2 : str.endsWith("=") ? 1 : 0;  //判断字符串结尾有几个'='
    byte[] bytes = new byte[str.length() * 3 / 4 - tempNum];     //删除对应个数
    int index = 0;
    //逆序读出明文
    for(int i = 0;i < str.length();i++){
        int c0 = toInt[str.charAt(i++)];    //Base64编码对应的索引
        int c1 =  toInt[str.charAt(i++)];
        bytes[index++] = (byte) ((c0 << 2) | (c1 >> 4));
        if(index >= bytes.length){
            return new String(bytes);
        }
        int c2 = toInt[str.charAt(i++)];
        bytes[index++] = (byte)((c1 << 4) | (c2 >> 2));
        if(index >= bytes.length){
            return new String(bytes);
        }
        int c3 = toInt[str.charAt(i)];
        bytes[index++] = (byte) ((c2 << 6) | c3);
    }
       return new String(bytes);

   }

}

测试可用:

MTIzNDU2
123456

猜你喜欢

转载自blog.csdn.net/qq_30764991/article/details/95041385