一篇文章彻底弄懂Base64编码原理

简介: 前半部分为转载,后半部分为自己补充----------------------------转载部分start-----------------------------

Base64的由来


目前Base64已经成为网络上常见的传输8Bit字节代码的编码方式之一。


在做支付系统时,系统之间的报文交互都需要使用Base64对明文进行转码,然后再进行签名或加密,之后再进行(或再次Base64)传输。那么,Base64到底起到什么作用呢?


在参数传输的过程中经常遇到的一种情况:使用全英文的没问题,但一旦涉及到中文就会出现乱码情况。


与此类似,网络上传输的字符并不全是可打印的字符,比如二进制文件、图片等。Base64的出现就是为了解决此问题,它是基于64个可打印的字符来表示二进制的数据的一种方法。


电子邮件刚问世的时候,只能传输英文,但后来随着用户的增加,中文、日文等文字的用户也有需求,但这些字符并不能被服务器或网关有效处理,因此Base64就登场了。随之,Base64在URL、Cookie、网页传输少量二进制文件中也有相应的使用。



Base64的编码原理


Base64的原理比较简单,每当我们使用Base64时都会先定义一个类似这样的数组:


['A', 'B', 'C', ... 'a', 'b', 'c', ... '0', '1', ... '+', '/']



上面就是Base64的索引表,字符选用了”A-Z、a-z、0-9、+、/” 64个可打印字符,这是标准的Base64协议规定。


在日常使用中我们还会看到“=”或“==”号出现在Base64的编码结果中,“=”在此是作为填充字符出现,后面会讲到。


具体转换步骤

第1步,将待转换的字符串每三个字节分为一组,每个字节占8bit,那么共有24个二进制位。

第2步,将上面的24个二进制位每6个一组,共分为4组。

第3步,在每组前面添加两个0,每组由6个变为8个二进制位,总共32个二进制位,即四个字节。

第4步,根据Base64编码对照表(见下图)获得对应的值。


0 A  17 R   34 i   51 z

1 B  18 S   35 j   52 0

2 C  19 T   36 k   53 1

3 D  20 U   37 l   54 2

4 E  21 V   38 m   55 3

5 F  22 W   39 n   56 4

6 G  23 X   40 o   57 5

7 H  24 Y   41 p   58 6

8 I  25 Z   42 q   59 7

9 J  26 a   43 r   60 8

10 K  27 b   44 s   61 9

11 L  28 c   45 t   62 +

12 M  29 d   46 u   63 /

13 N  30 e   47 v

14 O  31 f   48 w   

15 P  32 g   49 x

16 Q  33 h   50 y


从上面的步骤我们发现:

- Base64字符表中的字符原本用6个bit就可以表示,现在前面添加2个0,变为8个bit,会造成一定的浪费。因此,Base64编码之后的文本,要比原文大约三分之一。

- 为什么使用3个字节一组呢?因为6和8的最小公倍数为24,三个字节正好24个二进制位,每6个bit位一组,恰好能够分为4组。


示例说明

以下图的表格为示例,我们具体分析一下整个过程。




第1步:“M”、“a”、”n”对应的ASCII码值分别为77,97,110,对应的二进制值是01001101、01100001、01101110。如图第二三行所示,由此组成一个24位的二进制字符串。

第2步:如图红色框,将24位每6位二进制位一组分成四组。

第3步:在上面每一组前面补两个0,扩展成32个二进制位,此时变为四个字节:00010011、00010110、00000101、00101110。分别对应的值(Base64编码索引)为:19、22、5、46。

第4步:用上面的值在Base64编码表中进行查找,分别对应:T、W、F、u。因此“Man”Base64编码之后就变为:TWFu。

位数不足情况

上面是按照三个字节来举例说明的,如果字节数不足三个,那么该如何处理?




两个字节:两个字节共16个二进制位,依旧按照规则进行分组。此时总共16个二进制位,每6个一组,则第三组缺少2位,用0补齐,得到三个Base64编码,第四组完全没有数据则用“=”补上。因此,上图中“BC”转换之后为“QKM=”;

一个字节:一个字节共8个二进制位,依旧按照规则进行分组。此时共8个二进制位,每6个一组,则第二组缺少4位,用0补齐,得到两个Base64编码,而后面两组没有对应数据,都用“=”补上。因此,上图中“A”转换之后为“QQ==”;



注意事项


大多数编码都是由字符串转化成二进制的过程,而Base64的编码则是从二进制转换为字符串。与常规恰恰相反,

Base64编码主要用在传输、存储、表示二进制领域,不能算得上加密,只是无法直接看到明文。也可以通过打乱Base64编码来进行加密。

中文有多种编码(比如:utf-8、gb2312、gbk等),不同编码对应Base64编码结果都不一样。

延伸

上面我们已经看到了Base64就是用6位(2的6次幂就是64)表示字符,因此成为Base64。同理,Base32就是用5位,Base16就是用4位。大家可以按照上面的步骤进行演化一下。


Java 验证


最后,我们用一段Java代码来验证一下上面的转换结果:


import sun.misc.BASE64Encoder;

public class Base64Utils {

   public static void main(String[] args) {

       String man = "Man";

       String a = "A";

       String bc = "BC";

       BASE64Encoder encoder = new BASE64Encoder();

       System.out.println("Man base64结果为:" + encoder.encode(man.getBytes()));

       System.out.println("BC base64结果为:" + encoder.encode(bc.getBytes()));

       System.out.println("A base64结果为:" + encoder.encode(a.getBytes()));

   }

}


打印结果为:


Man base64结果为:TWFu

BC base64结果为:QkM=

A base64结果为:QQ==



以上结果与我们分析所得完全一致。


原文链接:https://www.choupangxia.com/topic/detail/61


----------------------------转载部分end-----------------------------



----------------------------补充内容 start-----------------------------


Base64URL

java.utni.Base64类的源码的字符提供了两种,一种是是普通的字符(rfc2045),一种是Url的字符(rf4648)。


https://tools.ietf.org/html/rfc4648


https://tools.ietf.org/html/rfc2045




提供了三个编码器


    static final Encoder RFC4648 = new Encoder(false, null, -1, true);

    static final Encoder RFC4648_URLSAFE = new Encoder(true, null, -1, true);

    static final Encoder RFC2045 = new Encoder(false, CRLF, MIMELINEMAX, true);

提供了对外函数


/**

    * Returns a {@link Encoder} that encodes using the

    * <a href="#basic">Basic</a> type base64 encoding scheme.

    *

    * @return  A Base64 encoder.

    */

   public static Encoder getEncoder() {

        return Encoder.RFC4648;

   }

   /**

    * Returns a {@link Encoder} that encodes using the

    * <a href="#url">URL and Filename safe</a> type base64

    * encoding scheme.

    *

    * @return  A Base64 encoder.

    */

   public static Encoder getUrlEncoder() {

        return Encoder.RFC4648_URLSAFE;

   }

   /**

    * Returns a {@link Encoder} that encodes using the

    * <a href="#mime">MIME</a> type base64 encoding scheme.

    *

    * @return  A Base64 encoder.

    */

   public static Encoder getMimeEncoder() {

       return Encoder.RFC2045;

   }

编码


   /**

        * Encodes all bytes from the specified byte array into a newly-allocated

        * byte array using the {@link Base64} encoding scheme. The returned byte

        * array is of the length of the resulting bytes.

        *

        * @param   src

        *          the byte array to encode

        * @return  A newly-allocated byte array containing the resulting

        *          encoded bytes.

        */

       public byte[] encode(byte[] src) {

           int len = outLength(src.length);          // dst array size

           byte[] dst = new byte[len];

           int ret = encode0(src, 0, src.length, dst);

           if (ret != dst.length)

                return Arrays.copyOf(dst, ret);

           return dst;

       }

/**

        * Encodes the specified byte array into a String using the {@link Base64}

        * encoding scheme.

        *

        * <p> This method first encodes all input bytes into a base64 encoded

        * byte array and then constructs a new String by using the encoded byte

        * array and the {@link java.nio.charset.StandardCharsets#ISO_8859_1

        * ISO-8859-1} charset.

        *

        * <p> In other words, an invocation of this method has exactly the same

        * effect as invoking

        * {@code new String(encode(src), StandardCharsets.ISO_8859_1)}.

        *

        * @param   src

        *          the byte array to encode

        * @return  A String containing the resulting Base64 encoded characters

        */

       @SuppressWarnings("deprecation")

       public String encodeToString(byte[] src) {

           byte[] encoded = encode(src);

           return new String(encoded, 0, 0, encoded.length);

       }


解码


    static final Decoder RFC4648         = new Decoder(false, false);

    static final Decoder RFC4648_URLSAFE = new Decoder(true, false);

    static final Decoder RFC2045         = new Decoder(false, true);

  /**

        * Decodes all bytes from the input byte array using the {@link Base64}

        * encoding scheme, writing the results into a newly-allocated output

        * byte array. The returned byte array is of the length of the resulting

        * bytes.

        *

        * @param   src

        *          the byte array to decode

        *

        * @return  A newly-allocated byte array containing the decoded bytes.

        *

        * @throws  IllegalArgumentException

        *          if {@code src} is not in valid Base64 scheme

        */

       public byte[] decode(byte[] src) {

           byte[] dst = new byte[outLength(src, 0, src.length)];

           int ret = decode0(src, 0, src.length, dst);

           if (ret != dst.length) {

               dst = Arrays.copyOf(dst, ret);

           }

           return dst;

       }

Base64Utils工具类介绍

Spring有一个工具类:Base64Utils,提供了base64的封装,底层用的是java.utni.Base64类。




看下源码,都是对编码和解码对象的封装


/*

* Copyright 2002-2017 the original author or authors.

*

* Licensed under the Apache License, Version 2.0 (the "License");

* you may not use this file except in compliance with the License.

* You may obtain a copy of the License at

*

*      https://www.apache.org/licenses/LICENSE-2.0

*

* Unless required by applicable law or agreed to in writing, software

* distributed under the License is distributed on an "AS IS" BASIS,

* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

* See the License for the specific language governing permissions and

* limitations under the License.

*/

package org.springframework.util;

import java.nio.charset.Charset;

import java.nio.charset.StandardCharsets;

import java.util.Base64;

/**

* A simple utility class for Base64 encoding and decoding.

*

* <p>Adapts to Java 8's {@link java.util.Base64} in a convenience fashion.

*

* @author Juergen Hoeller

* @author Gary Russell

* @since 4.1

* @see java.util.Base64

*/

public abstract class Base64Utils {

private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

/**

 * Base64-encode the given byte array.

 * @param src the original byte array

 * @return the encoded byte array

 */

public static byte[] encode(byte[] src) {

 if (src.length == 0) {

  return src;

 }

 return Base64.getEncoder().encode(src);

}

/**

 * Base64-decode the given byte array.

 * @param src the encoded byte array

 * @return the original byte array

 */

public static byte[] decode(byte[] src) {

 if (src.length == 0) {

  return src;

 }

 return Base64.getDecoder().decode(src);

}

/**

 * Base64-encode the given byte array using the RFC 4648

 * "URL and Filename Safe Alphabet".

 * @param src the original byte array

 * @return the encoded byte array

 * @since 4.2.4

 */

public static byte[] encodeUrlSafe(byte[] src) {

 if (src.length == 0) {

  return src;

 }

 return Base64.getUrlEncoder().encode(src);

}

/**

 * Base64-decode the given byte array using the RFC 4648

 * "URL and Filename Safe Alphabet".

 * @param src the encoded byte array

 * @return the original byte array

 * @since 4.2.4

 */

public static byte[] decodeUrlSafe(byte[] src) {

 if (src.length == 0) {

  return src;

 }

 return Base64.getUrlDecoder().decode(src);

}

/**

 * Base64-encode the given byte array to a String.

 * @param src the original byte array (may be {@code null})

 * @return the encoded byte array as a UTF-8 String

 */

public static String encodeToString(byte[] src) {

 if (src.length == 0) {

  return "";

 }

 return new String(encode(src), DEFAULT_CHARSET);

}

/**

 * Base64-decode the given byte array from an UTF-8 String.

 * @param src the encoded UTF-8 String

 * @return the original byte array

 */

public static byte[] decodeFromString(String src) {

 if (src.isEmpty()) {

  return new byte[0];

 }

 return decode(src.getBytes(DEFAULT_CHARSET));

}

/**

 * Base64-encode the given byte array to a String using the RFC 4648

 * "URL and Filename Safe Alphabet".

 * @param src the original byte array

 * @return the encoded byte array as a UTF-8 String

 */

public static String encodeToUrlSafeString(byte[] src) {

 return new String(encodeUrlSafe(src), DEFAULT_CHARSET);

}

/**

 * Base64-decode the given byte array from an UTF-8 String using the RFC 4648

 * "URL and Filename Safe Alphabet".

 * @param src the encoded UTF-8 String

 * @return the original byte array

 */

public static byte[] decodeFromUrlSafeString(String src) {

 return decodeUrlSafe(src.getBytes(DEFAULT_CHARSET));

}

}


特别需要注意的是 如果是对url进行编码,要使用


Base64Utils.encodeToUrlSafeString,因为默认的字符集中“+和/”在Url中有特殊含义。


   @Test

   public void testURL() {

       String url = "http://wwww.baidu.com/dfdfdfdf/dfdf=w测试哦rdfdfwe1231j2s+dfadfdf";

       System.out.println(Base64Utils.encodeToUrlSafeString(url.getBytes()));

       System.out.println(Base64Utils.encodeToString(url.getBytes()));

   }


————————————————

版权声明:本文为CSDN博主「明明如月学长」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/w605283073/article/details/89112566

相关文章
|
负载均衡 网络协议 算法
Nginx系列教程(13) - TCP反向代理实现
Nginx系列教程(13) - TCP反向代理实现
2055 1
|
存储 NoSQL Redis
redis set底层数据结构
set底层存储  redis的集合对象set的底层存储结构特别神奇,我估计一般人想象不到,底层使用了intset和hashtable两种数据结构存储的,intset我们可以理解为数组,hashtable就是普通的哈希表(key为set的值,value为null)。
6750 0
|
3月前
|
API Python
免费网络北京时间API接口
本文介绍如何通过接口盒子的免费API获取当前北京时间,支持多种格式及POST/GET请求方式。需注册账号获取ID和KEY,适用于服务器时间同步、日志记录等场景。
1355 6
|
11月前
|
存储 安全 算法
物联网发布者在发送数据时如何保证数据的安全性和完整性
数据加密、密钥管理和数据完整性验证是物联网安全的重要组成部分。对称加密(如AES)和非对称加密(如RSA)分别适用于大量数据和高安全需求的场景。密钥需安全存储并定期更新。数据完整性通过MAC(如HMAC-SHA256)和数字签名(如RSA签名)验证。通信协议如MQTT over TLS/SSL和CoAP over DTLS增强传输安全,确保数据在传输过程中的机密性和完整性。
|
11月前
|
JSON 测试技术 数据格式
Playwright 测试报告器
Playwright 测试报告器
388 4
|
安全 Java API
【新手必看】服务端集成网易云信IM 即时通讯
【新手必看】服务端集成网易云信IM 即时通讯
571 0
|
前端开发 JavaScript NoSQL
"从零到一:全方位解析现代Web开发技术栈
【7月更文挑战第9天】在当今快速发展的互联网时代,Web开发技术日新月异,为开发者提供了前所未有的创新空间。本文将从基础到高级,全面解析现代Web开发技术栈,帮助初学者或希望升级技能树的开发者构建稳固的知识体系。我们将探讨前端、后端以及全栈开发的关键技术,并通过一个简单的项目示例来演示这些技术的实际应用。
1608 1
|
存储
[ACTF新生赛2020]SoulLike 题解
[ACTF新生赛2020]SoulLike 题解
286 0
|
安全 Java Android开发
使用Unidbg进行安卓逆向实例讲解
使用Unidbg进行安卓逆向实例讲解
478 2
|
关系型数据库 MySQL
MySQL的5种时间类型的比较
MySQL的5种时间类型的比较