一.概念簡介
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位一組進行平分
010011 010110 000101 100011
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編碼表中查找字符
19 對應 T
22 對應 W
5 對應 F
35 對應 j (注意是小寫)
注意
- 若文本爲3個字符,則剛好編碼爲4個字符長度(3 8 = 4 6)
- 若文本爲2個字符,則編碼爲3個字符,尾部用一個"="補齊
- 若文本爲1個字符,則編碼爲2個字符,尾部用兩個"="補齊
四.Base58代碼實現
Base58是用於Bitcoin中使用的一種獨特的編碼方式,主要用於產生Bitcoin的錢包地址。
相比Base64,Base58不使用數字"0",字母大寫"O",字母大寫"I",和字母小寫"l",以及"+"和"/"符號。
設計Base58主要的目的是:
- 避免混淆。在某些字體下,數字0和字母大寫O,以及字母大寫I和字母小寫l會非常相似。
- 不使用"+"和"/"的原因是非字母或數字的字符串作爲帳號較難被接受。
- 沒有標點符號,通常不會被從中間分行。
- 大部分的軟件支持雙擊選擇整個字符串。
但是這個base58的計算量比base64的計算量多了很多。因爲58不是2的整數倍,需要不斷用除法去計算。
而且長度也比base64稍微多了一點。
附上golang的代碼實現
package main
import (
"math/big"
"bytes"
"fmt"
)
func main() {
/*
測試Base58
*/
//1.原始數據
data1 := []byte{10, 20, 30, 40, 50, 60}
data1 = append([]byte{0},data1...) //前綴+數據
fmt.Println("原始數據:",data1)
//Base58編碼
encode:=Base58Encode(data1)
fmt.Println("Base58編碼後:",encode) //[]byte
fmt.Println(string(encode))
//Base58解碼
decode:=Base58Decode(encode)
fmt.Println("Base58解碼後:",decode)
//測試數據
data2:="wangergou"
encode2:=Base58Encode([]byte(data2))
fmt.Println(encode2)
fmt.Println(string(encode2))
decode2:=Base58Decode(encode2)
fmt.Println(decode2)
fmt.Println(string(decode2))
fmt.Println(string(decode2[1:])) //wangergou
}
//base64
/*
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
0(零),O(大寫的o),I(大寫的i),l(小寫的L),+,/
*/
var b58Alphabet = []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
//字節數組轉Base58,加密
func Base58Encode(input []byte) []byte {
var result [] byte
x := big.NewInt(0).SetBytes(input)
//fmt.Println("x:",x)
base := big.NewInt(int64(len(b58Alphabet)))//58
//fmt.Println("base:",base)
zero := big.NewInt(0)
mod := &big.Int{}
for x.Cmp(zero) != 0 {
x.DivMod(x, base, mod)
//fmt.Println("x:",x,",mod:",mod) //0-57
result = append(result, b58Alphabet[mod.Int64()])
//fmt.Println("result:",string(result))
}
//將得到result中的數據進行反轉
ReverseBytes(result)
for b := range input { //遍歷input數組:index,value
if b == 0x00 {
result = append([]byte{b58Alphabet[0]}, result...)
} else {
break
}
}
//1 result
return result
}
//Base58轉字節數組,解密
func Base58Decode(input [] byte) []byte {
result := big.NewInt(0)
zeroBytes := 0
for b := range input {
if b == 0x00 {
zeroBytes++
}
}
fmt.Println("zeroBytes:",zeroBytes)
payload := input[zeroBytes:]
for _, b := range payload {
charIndex := bytes.IndexByte(b58Alphabet, b)
result.Mul(result, big.NewInt(58))
result.Add(result, big.NewInt(int64(charIndex)))
}
decoded := result.Bytes()
decoded = append(bytes.Repeat([]byte{byte(0x00)}, zeroBytes), decoded...)
return decoded
}
//字節數組反轉
func ReverseBytes(data []byte) {
for i, j := 0, len(data)-1; i < j; i, j = i+1, j-1 {
data[i], data[j] = data[j], data[i]
}
}