Java加密&解密-Base64

Base64

Base64 算法定义

Base64是一种基于64个字符的编码算法,根据RFC 2045的定义:Base64内容传送编码是一种以任意8位字节序列组成的描述形式,这种形式不容易被人直接识别。经过Base64编码后的数据会比原始数据略长,为原来的4/3倍数。经过Base64编码后的字符串的字数是以4为单位的整数倍。

Base64字符映射表

		/**
         * This array is a lookup table that translates 6-bit positive integer
         * index values into their "Base64 Alphabet" equivalents as specified
         * in "Table 1: The Base64 Alphabet" of RFC 2045 (and RFC 4648).
         */
        private static final char[] toBase64 = {
            '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',
            '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',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
        };
		/**
         * It's the lookup table for "URL and Filename safe Base64" as specified
         * in Table 2 of the RFC 4648, with the '+' and '/' changed to '-' and
         * '_'. This table is used when BASE64_URL is specified.
         */
        private static final char[] toBase64URL = {
            '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',
            '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',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'
        };

Url Base64算法

Url Base64算法主要是替换了Base64字符映射表中的第62和63个字符,也就是将"+"和"/"替换成了"-"和"_"。

实现原理

Base64算法主要是对给定的字符以字符编码(ASCII码,UTF-8码)对应的十进制数为基准,做编码操作:

  1. 将给定的字符串以字符为单位转换为对应的字符编码。
  2. 将获得的字符编码转换为二进制编码。
  3. 对获得的二进制码做分组转换操作,每3个8位二进制码为一组,转换为每4个6位二进制码为一组(不足6位时低位补0)。这是一个分组转换的过程,3个8位二进制码和4个6位二进制码的长度都是24位(3x8=4x6=24)。
  4. 对获得的4个6位二进制码补位,向6位二进制码添加2位高位0,组成4个8位二进制码。
  5. 将获得的4个8位二进制码转换为十进制码。
  6. 将获得的十进制码转换为Base64字符表中对应的字符。

示例代码

@Test
public void test7(){
    //Base64
    String inputStr = "Java Base64 Test";
    String ecode = Base64.getEncoder().encodeToString(inputStr.getBytes());
    System.out.println(ecode);
    String ouputStr = new String(Base64.getDecoder().decode(ecode), StandardCharsets.UTF_8);
    System.out.println(ouputStr);
    //Url Base64
    String urlInputStr = "https://www.baidu.com/";
    String ecodeUrl = Base64.getUrlEncoder().encodeToString(urlInputStr.getBytes());
    System.out.println(ecode);
    String urlOutputStr = new String(Base64.getUrlDecoder().decode(ecodeUrl), StandardCharsets.UTF_8);
    System.out.println(urlOutputStr);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值