• Base64编码


    Base64编码是一种编码,它不是MessageDigest(多对一映射),说它是一种密码有点牵强,因为这种密码太简单了,是最原始的密码.

    对于一个byte[]b,按照它是大头序来顺次读取每一个bit,每个6位做一个分隔,所得结果也按照大头序来解析.

    每个6位对应一个整数x,这个x决定了这个6位小分队应该用哪一个ascii码来表示.

    编码前的24个bit变成了4个6位小分队,表现形式是4个byte,所以编码之后长度变为原来的4/3=1.3333倍.

    下面给出Base64编码的java实现

    import java.util.Base64;
    import static java.lang.Math.*;
    class BitStream {
        byte[] b;
        // 需要补上几个字节,1个或者2个
        int add;
        // 长度,编码之后包含多少个有效字符
        int length;
        public BitStream(byte[] b) {
            this.b = b;
            length = (int) ceil(b.length / 3.0 * 4);
            add = (3 - b.length % 3) % 3;
        }
        // 获取第x个bit,其中byte的最高位为第一个bit,次高位为第二个bit...也就是说此流为大头序
        int getBit(int x) {
            if (x >= b.length * 8)
                return 0;
            return (b[x / 8] & (1 << (7 - x % 8))) == 0 ? 0 : 1;
        }
        // 获取第x个字符,其中6x+0为最高位,6x+1为次高位...也就是此流为大头序
        int get(int x) {
            int ans = 0;
            for (int i = 0; i < 6; i++) {
                ans = ans << 1 | getBit(x * 6 + i);
            }
            return ans;
        }
    }
    public class Base64Test {
        static String encode(byte[] b) {
            // 首先构造字符映射
            String map = "";
            for (char c = 'A'; c <= 'Z'; c++) {
                map += c;
            }
            for (char c = 'a'; c <= 'z'; c++) {
                map += c;
            }
            for (char c = '0'; c <= '9'; c++) {
                map += c;
            }
            map += "+/";
            String ans = "";
            BitStream cin = new BitStream(b);
            for (int i = 0; i < cin.length; i++) {
                ans += map.charAt(cin.get(i));
            }
            // 添加了几个字符就add几个字符
            ans += "==".substring(0, cin.add);
            return ans;
        }
        public static void main(String[] args) {
            byte[] bytes = "魏印福ad".getBytes();
            String s = Base64.getEncoder().encodeToString(bytes);
            System.out.println(s);
            System.out.println(encode(bytes));
        }
    }
  • 相关阅读:
    jieba分词
    hue审计记录-记录用户的查询记录(用户前端删除,后端也不会删除)
    nginx1.16.1平滑升级到1.18
    mysql5.7.24升级到5.7.30 rpm部署模式 redhat7
    ldap无法启动 system library:fopen:Permission denied bss_file.c:402
    hive练习-行列转换 窗口函数
    linkis重编译适配cdh
    redhat7 安装mysql5.15
    hive 自动加载分区 --动态分区
    最近搞了个客户端
  • 原文地址:https://www.cnblogs.com/weiyinfu/p/5907722.html
Copyright © 2020-2023  润新知