打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Base32.java

package com.raymon.bizos.pjt.util;

public class Base32 {

 private static final char[] ALPHABET = {

 ‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘, ‘G‘, ‘H‘,

 ‘I‘, ‘J‘, ‘K‘, ‘L‘, ‘M‘, ‘N‘, ‘O‘, ‘P‘,

 ‘Q‘, ‘R‘, ‘S‘, ‘T‘, ‘U‘, ‘V‘, ‘W‘, ‘X‘,

 ‘Y‘, ‘Z‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘

   };

   private static final byte[] DECODE_TABLE;

   static {

 DECODE_TABLE = new byte[128];

 for (int i = 0; i < DECODE_TABLE.length; i++) {

     DECODE_TABLE[i] = (byte) 0xFF;

 }

 for (int i = 0; i < ALPHABET.length; i++) {

     DECODE_TABLE[(int) ALPHABET[i]] = (byte) i;

     if (i < 24) {

  DECODE_TABLE[(int) Character.toLowerCase(ALPHABET[i])] = (byte) i;

     }

 }

   } 

 

   public static String encode(byte[] data) {

 char[] chars = new char[((data.length * 8) / 5)

          + ((data.length % 5) != 0 ? 1 : 0)];
 for (int i = 0, j = 0, index = 0; i < chars.length; i++) {

     if (index > 3) {

  int b = data[j] & (0xFF >> index);

  index = (index + 5) % 8;

  b <<= index;

  if (j < data.length - 1) {

      b |= (data[j + 1] & 0xFF) >> (8 - index);

               }

  chars[i] = ALPHABET[b];

               j++;

           }

           else {

  chars[i] = ALPHABET[((data[j] >> (8 - (index + 5))) & 0x1F)];

               index = (index + 5) % 8;

               if (index == 0) {

      j++;

               }

           }

 }

 return new String(chars);

   }
   public static byte[] decode(String s) throws Exception

   {

 char[] stringData = s.toCharArray();

 byte[] data = new byte[(stringData.length * 5) / 8];

 for (int i = 0, j = 0, index = 0; i < stringData.length; i++) {

     int val;

     try {

  val = DECODE_TABLE[stringData[i]];

     } catch(ArrayIndexOutOfBoundsException e) {

  throw new Exception("Illegal character");

     }

     if (val == 0xFF) {

  throw new Exception("Illegal character");

     }

     if (index <= 3) {

               index = (index + 5) % 8;

               if (index == 0) {

      data[j++] |= val;

               }

               else {

      data[j] |= val << (8 - index);

               }

           }

           else {

               index = (index + 5) % 8;

               data[j++] |= (val >> index);

               if (j < data.length) {

      data[j] |= val << (8 - index);

               }

           }

 }

 return data;

   }

}

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Base64加密算法源码(java版)
Java中byte数组与long数组相互转化
MQTT协议笔记之头部信息
Java 程序编码规范
初学入门:JAVA里字符编码的探索与理解 - 全部文章 - 技术学习
JAVA里字符编码 - Java - linxh
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服