80

BASE64编码原理与Golang代码调用

 5 years ago
source link: http://blog.51cto.com/clovemfong/2160384?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一.概念简介

Base64是一种基于64个可打印字符来表示二进制数据的表示方法。由于2^6=64,所以每6个比特为一个单元,对应某个可打印字符。3个字节有24个比特,对应于4个Base64单元,即3个字节可由4个可打印字符来表示。它可用来作为电子邮件的传输编码。在Base64中的可打印字符包括字母A-Z、a-z、数字0-9,这样共有62个字符,此外两个可打印符号在不同的系统中而不同。

Base64常用于在通常处理文本数据的场合,表示、传输、存储一些二进制数据

二.代码调用

在Golang中提供了代码库可以供我们直接调用,用于实现Base64的编码与解码,其提供了对两种格式的数据进行编码(与解码)

const encodeStd = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
const encodeURL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"

来自golang源码base64.go

1.标准数据(encodeStd)

msg := "Mac"
    //编码
    base64EncodedString := base64.StdEncoding.EncodeToString([]byte(msg))
    fmt.Println("Base64编码后:", base64EncodedString)
    //解码
    base64DecodedByte, err := base64.StdEncoding.DecodeString(base64EncodedString)
    if err != nil {
        log.Panic(err)
    }
    fmt.Println("Base64解码后的字节数组:", base64DecodedByte)
    fmt.Println("Base64解码后:", string(base64DecodedByte))

返回打印结果

Base64编码后: TWFj
Base64解码后的字节数组: [77 97 99]
Base64解码后: Mac

2.URL数据(encodeURL)

msgUrl :="http://www.google.com"
    base64UrlEncodedString :=base64.URLEncoding.EncodeToString([]byte(msgUrl))
    fmt.Println("Base64编码后:", base64UrlEncodedString)
    base64UrlDecodedByte,err := base64.URLEncoding.DecodeString(base64UrlEncodedString)
    if err !=nil {
        log.Panic(err)
    }
    fmt.Println("Base64解码后的字节数组:", base64UrlDecodedByte)
    fmt.Println("Base64解码后:", string(base64UrlDecodedByte))

返回打印结果

Base64编码后: aHR0cDovL3d3dy5nb29nbGUuY29t
Base64解码后的字节数组: [104 116 116 112 58 47 47 119 119 119 46 103 111 111 103 108 101 46 99 111 109]
Base64解码后: http://www.google.com

三.编码原理

1.将每个字符转成ASCII编码(10进制)

fmt.Println([]byte(msg)) //[77 97 99]

2.将10进制编码转成2进制编码

fmt.Printf("%b",[]byte(msg)) 
//[1001101 1100001 1100011]

补齐8位为:

[01001101 01100001 01100011]

3.将2进制编码按照6位一组进行平分

4.转成10进制数

010011 ==> 1x2^0 + 1x2^1 + 0 + 0 + 1x2^4 = 19

010110 ==> 0 + 1x2^1 + 1x2^2 + 0 + 1x2^4 = 22

000101 ==> 1x2^0 + 0 + 1 x 2^2 + 0 + 0 + 0 = 5

100011 ==> 1x2^0 + 1x2^1 + 0 + 0 + 0 + 1x2^5 = 35

5.将十进制数作为索引,从Base64编码表中查找字符

zaueuiF.png!web

19 对应 T
22 对应 W
5  对应 F
35 对应 j (注意是小写)

注意

  • 若文本为3个字符,则刚好编码为4个字符长度(3 8 = 4 6)
  • 若文本为2个字符,则编码为3个字符,尾部用一个"="补齐
  • 若文本为1个字符,则编码为2个字符,尾部用两个"="补齐

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK