在alibaba的fastjson中base64上增加的一些方法

package littlehow.base64;import java.nio.charset.Charset;
import java.util.Arrays;/*** 引用阿里巴巴fastjson中的base64工具* 自己实现encode方法* @author     wh* @createtime 2015-11-19 上午11:48:38**/
public class Base64 {public static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();public static final int[]  IA = new int[256];static {Arrays.fill(IA, -1);for (int i = 0, iS = CA.length; i < iS; i++)IA[CA[i]] = i;IA['='] = 0;}/*** Decodes a BASE64 encoded char array that is known to be resonably well formatted. The method is about twice as* fast as {@link #decode(char[])}. The preconditions are:<br>* + The array must have a line length of 76 chars OR no line separators at all (one line).<br>* + Line separator must be "\r\n", as specified in RFC 2045 + The array must not contain illegal characters within* the encoded string<br>* + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>** @param chars The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.* @return The decoded array of bytes. May be of length 0.*/public final static byte[] decodeFast(char[] chars, int offset, int charsLen) {// Check special caseif (charsLen == 0) {return new byte[0];}int sIx = offset, eIx = offset + charsLen - 1; // Start and end index after trimming.// Trim illegal chars from startwhile (sIx < eIx && IA[chars[sIx]] < 0)sIx++;// Trim illegal chars from endwhile (eIx > 0 && IA[chars[eIx]] < 0)eIx--;// get the padding count (=) (0, 1 or 2)int pad = chars[eIx] == '=' ? (chars[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end.int cCnt = eIx - sIx + 1; // Content count including possible separatorsint sepCnt = charsLen > 76 ? (chars[76] == '\r' ? cCnt / 78 : 0) << 1 : 0;int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytesbyte[] bytes = new byte[len]; // Preallocate byte[] of exact length// Decode all but the last 0 - 2 bytes.int d = 0;for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {// Assemble three bytes into an int from four "valid" characters.int i = IA[chars[sIx++]] << 18 | IA[chars[sIx++]] << 12 | IA[chars[sIx++]] << 6 | IA[chars[sIx++]];// Add the bytesbytes[d++] = (byte) (i >> 16);bytes[d++] = (byte) (i >> 8);bytes[d++] = (byte) i;// If line separator, jump over it.if (sepCnt > 0 && ++cc == 19) {sIx += 2;cc = 0;}}if (d < len) {// Decode last 1-3 bytes (incl '=') into 1-3 bytesint i = 0;for (int j = 0; sIx <= eIx - pad; j++)i |= IA[chars[sIx++]] << (18 - j * 6);for (int r = 16; d < len; r -= 8)bytes[d++] = (byte) (i >> r);}return bytes;}public final static byte[] decodeFast(String chars, int offset, int charsLen) {// Check special caseif (charsLen == 0) {return new byte[0];}int sIx = offset, eIx = offset + charsLen - 1; // Start and end index after trimming.// Trim illegal chars from startwhile (sIx < eIx && IA[chars.charAt(sIx)] < 0)sIx++;// Trim illegal chars from endwhile (eIx > 0 && IA[chars.charAt(eIx)] < 0)eIx--;// get the padding count (=) (0, 1 or 2)int pad = chars.charAt(eIx) == '=' ? (chars.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count '=' at end.int cCnt = eIx - sIx + 1; // Content count including possible separatorsint sepCnt = charsLen > 76 ? (chars.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0;int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytesbyte[] bytes = new byte[len]; // Preallocate byte[] of exact length// Decode all but the last 0 - 2 bytes.int d = 0;for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {// Assemble three bytes into an int from four "valid" characters.int i = IA[chars.charAt(sIx++)] << 18 | IA[chars.charAt(sIx++)] << 12 | IA[chars.charAt(sIx++)] << 6 | IA[chars.charAt(sIx++)];// Add the bytesbytes[d++] = (byte) (i >> 16);bytes[d++] = (byte) (i >> 8);bytes[d++] = (byte) i;// If line separator, jump over it.if (sepCnt > 0 && ++cc == 19) {sIx += 2;cc = 0;}}if (d < len) {// Decode last 1-3 bytes (incl '=') into 1-3 bytesint i = 0;for (int j = 0; sIx <= eIx - pad; j++)i |= IA[chars.charAt(sIx++)] << (18 - j * 6);for (int r = 16; d < len; r -= 8)bytes[d++] = (byte) (i >> r);}return bytes;}/*** Decodes a BASE64 encoded string that is known to be resonably well formatted. The method is about twice as fast* as {@link #decode(String)}. The preconditions are:<br>* + The array must have a line length of 76 chars OR no line separators at all (one line).<br>* + Line separator must be "\r\n", as specified in RFC 2045 + The array must not contain illegal characters within* the encoded string<br>* + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>** @param s The source string. Length 0 will return an empty array. <code>null</code> will throw an exception.* @return The decoded array of bytes. May be of length 0.*/public final static byte[] decodeFast(String s) {// Check special caseint sLen = s.length();if (sLen == 0) {return new byte[0];}int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.// Trim illegal chars from startwhile (sIx < eIx && IA[s.charAt(sIx) & 0xff] < 0)sIx++;// Trim illegal chars from endwhile (eIx > 0 && IA[s.charAt(eIx) & 0xff] < 0)eIx--;// get the padding count (=) (0, 1 or 2)int pad = s.charAt(eIx) == '=' ? (s.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count '=' at end.int cCnt = eIx - sIx + 1; // Content count including possible separatorsint sepCnt = sLen > 76 ? (s.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0;int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytesbyte[] dArr = new byte[len]; // Preallocate byte[] of exact length// Decode all but the last 0 - 2 bytes.int d = 0;for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {// Assemble three bytes into an int from four "valid" characters.int i = IA[s.charAt(sIx++)] << 18 | IA[s.charAt(sIx++)] << 12 | IA[s.charAt(sIx++)] << 6| IA[s.charAt(sIx++)];// Add the bytesdArr[d++] = (byte) (i >> 16);dArr[d++] = (byte) (i >> 8);dArr[d++] = (byte) i;// If line separator, jump over it.if (sepCnt > 0 && ++cc == 19) {sIx += 2;cc = 0;}}if (d < len) {// Decode last 1-3 bytes (incl '=') into 1-3 bytesint i = 0;for (int j = 0; sIx <= eIx - pad; j++)i |= IA[s.charAt(sIx++)] << (18 - j * 6);for (int r = 16; d < len; r -= 8)dArr[d++] = (byte) (i >> r);}return dArr;}//  ############################# 以下不属于fast json base64 内容  ##########################public static String decode(String s){try {return new String(decodeFast(s), UTF8);} catch (Exception e) {return null;}}public static String decodeGbk(String s){try {return new String(decodeFast(s), GBK);} catch (Exception e) {return null;}}/** 编码方式 */public static final Charset UTF8 = Charset.forName("UTF-8");public static final Charset GBK = Charset.forName("GBK");/*** 按照utf-8编码字符* @param s  -- 待编码字符* @return*/public static String encode(String s){try{return encode(s.getBytes(UTF8));}catch(Exception e){e.printStackTrace();return null;}}/*** 按照gbk解码字符* @param s* @return*/public static String encodeGbk(String s){try{return encode(s.getBytes(GBK));}catch(Exception e){e.printStackTrace();return null;}}/*** base编码* @param target* @return*/public static String encode(byte[] target){if(target==null||target.length==0) return null;int length = target.length;/** 判断最后补位数 */int replenish = length%3;/** 判断target长度是否为总循环次数 */int loop = length/3 + (replenish==0?0:1);byte[] ret = new byte[4 * loop];/** 下标 */int index = 0;int retIndex = 0;int one,two,three;while((--loop)>0){one = target[index++] & 0xff;two = target[index++] & 0xff;three = target[index++] & 0xff;ret[retIndex++] = (byte)CA[one>>>2&0x3f];ret[retIndex++] = (byte)CA[(one<<4|two>>>4)&0x3f];ret[retIndex++] = (byte)CA[(two<<2|three>>>6)&0x3f];ret[retIndex++] = (byte)CA[three&0x3f];}//判断最后是否还有剩余,有补等号的情况出现switch(replenish){case 0:one = target[index++] & 0xff;two = target[index++] & 0xff;three = target[index++] & 0xff;ret[retIndex++] = (byte)CA[one>>>2&0x3f];ret[retIndex++] = (byte)CA[(one<<4|two>>>4)&0x3f];ret[retIndex++] = (byte)CA[(two<<2|three>>>6)&0x3f];ret[retIndex++] = (byte)CA[three&0x3f];break;case 1://补两个=one = target[length-1] & 0xff;ret[retIndex++] = (byte)CA[one>>>2&0x3f];ret[retIndex++] = (byte)CA[one<<4&0x3f];ret[retIndex++] = (byte) '=';ret[retIndex++] = (byte) '=';break;case 2://补一个=one = target[target.length - 2] & 0xff;two = target[target.length - 1] & 0xff;ret[retIndex++] = (byte)CA[one>>>2&0x3f];ret[retIndex++] = (byte)CA[(one<<4|two>>>4)&0x3f];ret[retIndex++] = (byte)CA[two<<2 & 0x3f];ret[retIndex++] = (byte) '=';break;}return new String(ret);}
}

java编解码base64相关推荐

  1. 3.2 Java编解码场景及实现

    篇幅还是较长,不知道怎么来分割,索性就一起了 在阅读的过程中,一定要不忘初心(想想为什么学编解码) 正片开始 Java的编解码具体实现 ​ 这里将以实际例子介绍 Java 中如何实现编码及解码,下面我 ...

  2. java tlv生成,TLV格式数据JAVA编解码

    电信系统中不少通信数据都采用TLV格式进行二进制编解码,而具体的TLV格式并无统一的规范,只能算是一种统称,其规定了数据中的相应字段都由Tag-Length-Value三要素组成,有些协议对于固定长度 ...

  3. 编解码base64、对称加密aes和非对称加密rsa

    base64 :(兼容所有bit8位的字符,然后用64种字符进行转码,达到一致性) 意思就是:考虑到多语言原因,有的特殊字符传输不兼容,因为很多都是只支持ASSIC码,那么特殊字符就会找不到对应的AS ...

  4. js编码java解码_JS编解码与Java编解码的对应关系

    最近前段在导出数据时会遇到"illegal character"的异常错误,结果发现是在请求地址中请求参数包含了空白字符(其编码为%C2%A0)或者是空格字符(其编码为%20),之 ...

  5. Java 编解码问题

    ASCII 计算机在美国发明后,为了将用到的一些字符存储到计算机中,将可见字符(英文字母.数字.标点符号)和控制字符(回车.换行...)按顺序罗列出来,用0~127对所需字符进行编号.将0~127的编 ...

  6. Jva编解码,加密工具类大全(Base64编解码,URL 编解码,sha56_Hmac加密,MD5对字符串进行加密,java自带类实现SHA-256方式加密)

    Base64编解码 /*** Base64编码.*/public static String encodeBase64(byte[] input) {return new String(Base64. ...

  7. ubuntu下c++中base64编解码测试和图片编解码测试

    全栈工程师开发手册 (作者:栾鹏) 架构系列文章 字符数组的base64编解码 base64.h #include <string>std::string base64_encode(un ...

  8. java实现asn.1解码_ASN1编解码实现方法

    第1章概述 1.1背景 系统与充值平台的接口是文件的方式,充值平台将文件内容以ASN.1方式进行编码,系统需要根据ASN.1协议进行解码. 关于ASN.1开发的资料,网上资料非常少,特别是涉及到具体的 ...

  9. java asn.1_ASN1编解码实现方法 | 学步园

    第1章概述 1.1背景 系统与充值平台的接口是文件的方式,充值平台将文件内容以ASN.1方式进行编码,系统需要根据ASN.1协议进行解码. 关于ASN.1开发的资料,网上资料非常少,特别是涉及到具体的 ...

最新文章

  1. css3 混合,瞧瞧CSS3的混合模式
  2. Excel 技巧篇-公式实现在指定范围内生成指定小数位的随机数
  3. 十个免费的WEB压力测试工具
  4. Oracle定义变量、常量
  5. android wifi
  6. k8s 基础概念和术语
  7. 李航《统计学习方法》笔记
  8. 【iCore4 双核心板_FPGA】例程十一:FSMC总线通信实验——独立地址模式
  9. 联想开机启动项按哪个_win7系统如何修改系统启动项 win7系统修改系统启动项方法【步骤】...
  10. qt调用外部程序(exe)
  11. SQL语句执行优先级
  12. bp神经网络图像压缩原理图,bp神经网络图像分类
  13. 360导致某些页面变为淡绿色
  14. kettle怎么复制资源库的job_kettle插件更新:定时执行资源库及文件的ktr和kjb作业...
  15. 明日传奇第三季/全集Legends of Tomorrow迅雷下载
  16. 详细介绍百度ERNIE 2.0:A Continual Pre-Training Framework for Language Understanding
  17. JSP入门教程:JSP简明教程
  18. 什么样的人适合做项目经理
  19. 影子价格的经济学意义和特点
  20. 妖怪屋 服务器维护中,《阴阳师:妖怪屋》3月3日维护更新公告

热门文章

  1. Google,Verizon和网络中立性辩论
  2. 基金从业考试报名时间?
  3. squid代理服务之透明代理的配置方法
  4. JS中单击多次执行一次的问题
  5. 教程 | 各省电力缺口有多大,看看这张电力大数据地图
  6. Aurora论文解读
  7. 如何使用Python在OpenCV中检测图像中的猫脸?
  8. SVM求硬间隔最大超平面
  9. 读优化阵列信号处理------窄带部分读书笔记
  10. Jzoj3486 道路改建