Base64工具类

简介: Base64工具类
package com.fly.util.Base64;
/**
 * @Title: Base64工具类
 * @ClassName: com.newcapec.util.Base64.Base64.java
 * @Description:
 *
 * @author: FLY
 * @date:  2017-10-18 17:10
 * @version V1.0
 */
public class Base64 {
    private static final byte[] encodingTable = {
            (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E',
            (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J',
            (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O',
            (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T',
            (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y',
            (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd',
            (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i',
            (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n',
            (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's',
            (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x',
            (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2',
            (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7',
            (byte) '8', (byte) '9', (byte) '+', (byte) '/'
    };
    private static final byte[] decodingTable;
    static {
        decodingTable = new byte[128];
        for (int i = 0; i < 128; i++) {
            decodingTable[i] = (byte) -1;
        }
        for (int i = 'A'; i <= 'Z'; i++) {
            decodingTable[i] = (byte) (i - 'A');
        }
        for (int i = 'a'; i <= 'z'; i++) {
            decodingTable[i] = (byte) (i - 'a' + 26);
        }
        for (int i = '0'; i <= '9'; i++) {
            decodingTable[i] = (byte) (i - '0' + 52);
        }
        decodingTable['+'] = 62;
        decodingTable['/'] = 63;
    }
    /**
     * @Title: 编码
     * @methodName:  encode
     * @param data【byte[]】
     * @param offset 【int】
     * @return byte[]
     * @Description:
     *
     * @author: FLY
     * @date:  2017-10-18 17:11
     */
    public static byte[] encode(byte[] data, int offset) {
        byte[] bytes;
        int realCount = data.length - offset;
        int modulus = realCount % 3;
        if (modulus == 0) {
            bytes = new byte[(4 * realCount) / 3];
        } else {
            bytes = new byte[4 * ((realCount / 3) + 1)];
        }
        int dataLength = (data.length - modulus);
        int a1;
        int a2;
        int a3;
        for (int i = offset, j = 0; i < dataLength; i += 3, j += 4) {
            a1 = data[i] & 0xff;
            a2 = data[i + 1] & 0xff;
            a3 = data[i + 2] & 0xff;
            bytes[j] = encodingTable[(a1 >>> 2) & 0x3f];
            bytes[j + 1] = encodingTable[((a1 << 4) | (a2 >>> 4)) & 0x3f];
            bytes[j + 2] = encodingTable[((a2 << 2) | (a3 >>> 6)) & 0x3f];
            bytes[j + 3] = encodingTable[a3 & 0x3f];
        }
        int b1;
        int b2;
        int b3;
        int d1;
        int d2;
        switch (modulus) {
            case 0: /* nothing left to do */
                break;
            case 1:
                d1 = data[data.length - 1] & 0xff;
                b1 = (d1 >>> 2) & 0x3f;
                b2 = (d1 << 4) & 0x3f;
                bytes[bytes.length - 4] = encodingTable[b1];
                bytes[bytes.length - 3] = encodingTable[b2];
                bytes[bytes.length - 2] = (byte) '=';
                bytes[bytes.length - 1] = (byte) '=';
                break;
            case 2:
                d1 = data[data.length - 2] & 0xff;
                d2 = data[data.length - 1] & 0xff;
                b1 = (d1 >>> 2) & 0x3f;
                b2 = ((d1 << 4) | (d2 >>> 4)) & 0x3f;
                b3 = (d2 << 2) & 0x3f;
                bytes[bytes.length - 4] = encodingTable[b1];
                bytes[bytes.length - 3] = encodingTable[b2];
                bytes[bytes.length - 2] = encodingTable[b3];
                bytes[bytes.length - 1] = (byte) '=';
                break;
        }
        return bytes;
    }
    /**
     * @Title: 解码
     * @methodName:  decode
     * @param data 【byte[]】
     * @return byte[]
     * @Description:
     *
     * @author: FLY
     * @date:  2017-10-18 17:12
     */
    public static byte[] decode(byte[] data) {
        byte[] bytes;
        byte b1;
        byte b2;
        byte b3;
        byte b4;
        data = discardNonBase64Bytes(data);
        if (data[data.length - 2] == '=') {
            bytes = new byte[(((data.length / 4) - 1) * 3) + 1];
        } else if (data[data.length - 1] == '=') {
            bytes = new byte[(((data.length / 4) - 1) * 3) + 2];
        } else {
            bytes = new byte[((data.length / 4) * 3)];
        }
        for (int i = 0, j = 0; i < (data.length - 4); i += 4, j += 3) {
            b1 = decodingTable[data[i]];
            b2 = decodingTable[data[i + 1]];
            b3 = decodingTable[data[i + 2]];
            b4 = decodingTable[data[i + 3]];
            bytes[j] = (byte) ((b1 << 2) | (b2 >> 4));
            bytes[j + 1] = (byte) ((b2 << 4) | (b3 >> 2));
            bytes[j + 2] = (byte) ((b3 << 6) | b4);
        }
        if (data[data.length - 2] == '=') {
            b1 = decodingTable[data[data.length - 4]];
            b2 = decodingTable[data[data.length - 3]];
            bytes[bytes.length - 1] = (byte) ((b1 << 2) | (b2 >> 4));
        } else if (data[data.length - 1] == '=') {
            b1 = decodingTable[data[data.length - 4]];
            b2 = decodingTable[data[data.length - 3]];
            b3 = decodingTable[data[data.length - 2]];
            bytes[bytes.length - 2] = (byte) ((b1 << 2) | (b2 >> 4));
            bytes[bytes.length - 1] = (byte) ((b2 << 4) | (b3 >> 2));
        } else {
            b1 = decodingTable[data[data.length - 4]];
            b2 = decodingTable[data[data.length - 3]];
            b3 = decodingTable[data[data.length - 2]];
            b4 = decodingTable[data[data.length - 1]];
            bytes[bytes.length - 3] = (byte) ((b1 << 2) | (b2 >> 4));
            bytes[bytes.length - 2] = (byte) ((b2 << 4) | (b3 >> 2));
            bytes[bytes.length - 1] = (byte) ((b3 << 6) | b4);
        }
        return bytes;
    }
    /**
     * @Title: 解码
     * @methodName:  decode
     * @param data 【String】
     * @return byte[]
     * @Description:
     *
     * @author: FLY
     * @date:  2017-10-18 17:13
     */
    public static byte[] decode(String data) {
        byte[] bytes;
        byte b1;
        byte b2;
        byte b3;
        byte b4;
        data = discardNonBase64Chars(data);
        if (data.charAt(data.length() - 2) == '=') {
            bytes = new byte[(((data.length() / 4) - 1) * 3) + 1];
        } else if (data.charAt(data.length() - 1) == '=') {
            bytes = new byte[(((data.length() / 4) - 1) * 3) + 2];
        } else {
            bytes = new byte[((data.length() / 4) * 3)];
        }
        for (int i = 0, j = 0; i < (data.length() - 4); i += 4, j += 3) {
            b1 = decodingTable[data.charAt(i)];
            b2 = decodingTable[data.charAt(i + 1)];
            b3 = decodingTable[data.charAt(i + 2)];
            b4 = decodingTable[data.charAt(i + 3)];
            bytes[j] = (byte) ((b1 << 2) | (b2 >> 4));
            bytes[j + 1] = (byte) ((b2 << 4) | (b3 >> 2));
            bytes[j + 2] = (byte) ((b3 << 6) | b4);
        }
        if (data.charAt(data.length() - 2) == '=') {
            b1 = decodingTable[data.charAt(data.length() - 4)];
            b2 = decodingTable[data.charAt(data.length() - 3)];
            bytes[bytes.length - 1] = (byte) ((b1 << 2) | (b2 >> 4));
        } else if (data.charAt(data.length() - 1) == '=') {
            b1 = decodingTable[data.charAt(data.length() - 4)];
            b2 = decodingTable[data.charAt(data.length() - 3)];
            b3 = decodingTable[data.charAt(data.length() - 2)];
            bytes[bytes.length - 2] = (byte) ((b1 << 2) | (b2 >> 4));
            bytes[bytes.length - 1] = (byte) ((b2 << 4) | (b3 >> 2));
        } else {
            b1 = decodingTable[data.charAt(data.length() - 4)];
            b2 = decodingTable[data.charAt(data.length() - 3)];
            b3 = decodingTable[data.charAt(data.length() - 2)];
            b4 = decodingTable[data.charAt(data.length() - 1)];
            bytes[bytes.length - 3] = (byte) ((b1 << 2) | (b2 >> 4));
            bytes[bytes.length - 2] = (byte) ((b2 << 4) | (b3 >> 2));
            bytes[bytes.length - 1] = (byte) ((b3 << 6) | b4);
        }
        for (int i = 0; i < bytes.length; i++) {
            System.out.println("," + bytes[i]);
        }
        return bytes;
    }
    /**
     * @Title: 摒弃非Base64的字节
     * @methodName:  discardNonBase64Bytes
     * @param data
     * @return byte[]
     * @Description:
     *
     * @author: FLY
     * @date:  2017-10-18 17:15
     */
    private static byte[] discardNonBase64Bytes(byte[] data) {
        byte[] temp = new byte[data.length];
        int bytesCopied = 0;
        for (int i = 0; i < data.length; i++) {
            if (isValidBase64Byte(data[i])) {
                temp[bytesCopied++] = data[i];
            }
        }
        byte[] newData = new byte[bytesCopied];
        System.arraycopy(temp, 0, newData, 0, bytesCopied);
        return newData;
    }
    /**
     * @Title: 摒弃非Base64的字符
     * @methodName:  discardNonBase64Chars
     * @param data
     * @return java.lang.String
     * @Description:
     *
     * @author: FLY
     * @date:  2017-10-18 17:19
     */
    private static String discardNonBase64Chars(String data) {
        StringBuffer sb = new StringBuffer();
        int length = data.length();
        for (int i = 0; i < length; i++) {
            if (isValidBase64Byte((byte) (data.charAt(i)))) {
                sb.append(data.charAt(i));
            }
        }
        return sb.toString();
    }
    /**
     * @Title: Base64Byte校验
     * @methodName:  isValidBase64Byte
     * @param b
     * @return boolean
     * @Description:
     *
     * @author: FLY
     * @date:  2017-10-18 17:17
     */
    private static boolean isValidBase64Byte(byte b) {
        if (b == '=') {
            return true;
        } else if ((b < 0) || (b >= 128)) {
            return false;
        } else if (decodingTable[b] == -1) {
            return false;
        }
        return true;
    }
    /**
     * @Title: 编码
     * @methodName:  encode
     * @param data
     * @param charset 字符集
     * @return java.lang.String
     * @Description:
     *
     * @author: FLY
     * @date:  2017-10-18 17:16
     */
    public static String encode(String data, String charset) throws Exception {
        // byte[] result = (data.getBytes("Unicode"));
        if (data == null || data.length() == 0) {
            return data;
        }
        int offset = 0;
        // getBytes("unicode")转完后会在前头加上两字节”FE“
        byte[] result = encode(data.getBytes(charset), offset);
        StringBuffer sb = new StringBuffer(result.length);
        for (int i = 0; i < result.length; i++) {
            sb.append((char) result[i]);
        }
        return sb.toString();
    }
    /**
     * @Title:  解码
     * @methodName:  decode
     * @param data
     * @param charset 字符集
     * @return java.lang.String
     * @Description:
     *
     * @author: FLY
     * @date:  2017-10-18 17:15
     */
    public static String decode(String data, String charset) throws Exception {
        if (data == null || data.length() == 0) {
            return data;
        }
        return new String(Base64.decode(data), charset);
    }
    public static void main(String[] args) throws Exception {
        String data = "我们";
        String data1 = encode(data, "Unicode");
        String data2 = decode(data1, "Unicode");
        System.out.println(data);
        System.out.println(data1);
        System.out.println(data2);
    }
}
相关文章
|
应用服务中间件 Linux PHP
深入理解Nginx工作原理及优化技巧(上)
深入理解Nginx工作原理及优化技巧
深入理解Nginx工作原理及优化技巧(上)
|
设计模式 算法 程序员
程序员为何需要反复修改Bug?探寻代码编写中的挑战与现实
作为开发者,我们在日常开发过程中,往往会遇到反复修改bug的情况,而且不能一次性把代码写的完美无瑕,其实开发项目是一项复杂而富有挑战性的任务,即使经验丰富的程序员也难以在一次性编写完美无瑕地完成代码,我个人觉得一次性写好代码是不可能完成的事情。虽然在设计之初已经尽力思考全面,并在实际操作中力求精确,但程序员仍然需要花费大量时间和精力来调试和修复Bug。那么本文就来分享程序员需要反复修改Bug的原因,以及在开发中所面临的复杂性与挑战。
485 1
程序员为何需要反复修改Bug?探寻代码编写中的挑战与现实
|
资源调度
There appears to be trouble with your network connection.Retrying
There appears to be trouble with your network connection.Retrying
2224 0
There appears to be trouble with your network connection.Retrying
|
8月前
|
存储 缓存 编解码
阿里云服务器实例规格怎么选?经济型、通用算力型、计算型、通用型、内存型场景化选购指南
阿里云服务器的实例规格有经济型、通用型、计算型、内存型、通用算力型、大数据型、本地SSD型、高主频型、突发型、共享型等不同种类的实例规格,以满足不同用户和业务场景的需求。对于初次接触阿里云服务器的用户来说,如何选择合适的实例规格成为了一个重要的问题。本文将为大家解析阿里云的经济型、通用算力型、计算型、通用型和内存型实例规格的主要性能和适用场景情况,帮助用户根据实际需求选择合适的云服务器实例。
801 10
|
SQL Java 关系型数据库
MyCAT----读写分离
MyCAT 是一款用 Java 开发的开源数据库中间件,需在 JDK7 以上环境运行。它位于应用与数据库间,负责数据处理与交互,支持读写分离与分库分表。部署时需先安装 JDK,再下载解压 MyCAT,并配置 `server.xml` 和 `schema.xml` 文件定义用户、逻辑库及数据节点。启动 MyCAT 后,可通过 SQL 客户端验证读写分离策略。
|
敏捷开发 存储 安全
潜力与限制:低代码开发平台优缺点全面分析
低代码开发平台加速企业数字化转型,优点包括快速开发、降低技术门槛、灵活定制和方便维护。然而,也存在复杂功能限制、数据孤岛、供应商依赖和安全合规问题。推荐的低代码平台有Zoho Creator(适合中小企业)、Mendix(创新型企业)、Microsoft Power Apps(大型企业)、OutSystems(高安全合规要求)以及AppSheet和Appian(入门级用户)。在选择时,需综合考虑业务需求、技术因素和风险。
1354 0
|
Linux Docker 索引
CentOS7安装Docker
CentOS7安装Docker
365 6
|
机器学习/深度学习 编解码 监控
算法金 | 深度学习图像增强方法总结
**图像增强技术概括** 图像增强聚焦于提升视觉效果和细节,广泛应用于医学、遥感等领域。空间域增强包括直方图均衡化(增强对比度)、对比度拉伸、灰度变换、平滑滤波(均值、中值)和锐化滤波(拉普拉斯、高通)。频率域增强利用傅里叶变换、小波变换,通过高频和低频滤波增强图像特征。现代方法涉及超分辨率重建、深度学习去噪(如CNN、Autoencoder)、图像修复(如GAN)和GANs驱动的多种图像处理任务。
809 14
算法金 | 深度学习图像增强方法总结
|
Ubuntu 开发工具 git
在Ubuntu 18.04上安装Git【快速入门】
在Ubuntu 18.04上安装Git【快速入门】
259 0
|
SQL 存储 安全
【SQL刷题】Day3----SQL必会的常用函数专项练习
【SQL刷题】Day3----SQL必会的常用函数专项练习
350 0
【SQL刷题】Day3----SQL必会的常用函数专项练习