Skip to content

golang使用base64编码

Published:

golang标准库中提供了base64的内置支持

encoding/base64 提供了 4 种模式

URL 编码和标准编码的区别是使用 -_ 替换了 +/

package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	msg := []byte("Hello Golang!窗前明月光,疑是地上霜,举头望明月,低头思故乡")

	encoded := base64.StdEncoding.EncodeToString([]byte(msg))
	fmt.Println(encoded)
    // SGVsbG8gR29sYW5nIeeql+WJjeaYjuaciOWFiSznlpHmmK/lnLDkuIrpnJws5Li+5aS05pyb5piO5pyILOS9juWktOaAneaVheS5oQ==

	decoded, _ := base64.StdEncoding.DecodeString(encoded)
	fmt.Println(string(decoded))
    // Hello Golang!窗前明月光,疑是地上霜,举头望明月,低头思故乡


	encoded = base64.RawStdEncoding.EncodeToString([]byte(msg))
	fmt.Println(encoded)
    // SGVsbG8gR29sYW5nIeeql+WJjeaYjuaciOWFiSznlpHmmK/lnLDkuIrpnJws5Li+5aS05pyb5piO5pyILOS9juWktOaAneaVheS5oQ

	decoded, _ = base64.RawStdEncoding.DecodeString(encoded)
	fmt.Println(string(decoded))
    // Hello Golang!窗前明月光,疑是地上霜,举头望明月,低头思故乡


	encoded = base64.URLEncoding.EncodeToString([]byte(msg))
	fmt.Println(encoded)
    // SGVsbG8gR29sYW5nIeeql-WJjeaYjuaciOWFiSznlpHmmK_lnLDkuIrpnJws5Li-5aS05pyb5piO5pyILOS9juWktOaAneaVheS5oQ==

	decoded, _ = base64.URLEncoding.DecodeString(encoded)
	fmt.Println(string(decoded))
    // Hello Golang!窗前明月光,疑是地上霜,举头望明月,低头思故乡


	encoded = base64.RawURLEncoding.EncodeToString([]byte(msg))
	fmt.Println(encoded)
    // SGVsbG8gR29sYW5nIeeql-WJjeaYjuaciOWFiSznlpHmmK_lnLDkuIrpnJws5Li-5aS05pyb5piO5pyILOS9juWktOaAneaVheS5oQ

	decoded, _ = base64.RawURLEncoding.DecodeString(encoded)
	fmt.Println(string(decoded))
    // Hello Golang!窗前明月光,疑是地上霜,举头望明月,低头思故乡
}

标准库中也提供了自定义字母表和替换填充字符的方法

package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	msg := []byte("Hello Golang!窗前明月光,疑是地上霜,举头望明月,低头思故乡")

	// 需要提供长度为64的字母表,默认使用=作为填充字符
	CustomEncoding := base64.NewEncoding("ZYXWVUTSRQPONMLKJIHGFEDCBA~9876543210^zyxwvutsrqponmlkjihgfedcba")

	encoded := CustomEncoding.EncodeToString(msg)
	fmt.Println(encoded)
	// HTEt9Td4IjctBDgyR66v^bDQ16~B1r~82LDU2Hmy^wSzzPa^yOW0rRuwyQptgO2bg~Hlgwn9gw2LgwnROLHc1rD0sL~Zy6~E36HgxJ==

	decoded, _ := CustomEncoding.DecodeString(encoded)
	fmt.Println(string(decoded))
	// Hello Golang!窗前明月光,疑是地上霜,举头望明月,低头思故乡


	// 使用WithPadding来禁用填充
	RawCustomEncoding := CustomEncoding.WithPadding(base64.NoPadding)

	encoded = RawCustomEncoding.EncodeToString(msg)
	fmt.Println(encoded)
	// HTEt9Td4IjctBDgyR66v^bDQ16~B1r~82LDU2Hmy^wSzzPa^yOW0rRuwyQptgO2bg~Hlgwn9gw2LgwnROLHc1rD0sL~Zy6~E36HgxJ

	decoded, _ = RawCustomEncoding.DecodeString(encoded)
	fmt.Println(string(decoded))
	// Hello Golang!窗前明月光,疑是地上霜,举头望明月,低头思故乡


	// 使用@替换填充字符
	CustomEncodingWithAt := CustomEncoding.WithPadding('@')
	encoded = CustomEncodingWithAt.EncodeToString(msg)
	fmt.Println(encoded)
	// HTEt9Td4IjctBDgyR66v^bDQ16~B1r~82LDU2Hmy^wSzzPa^yOW0rRuwyQptgO2bg~Hlgwn9gw2LgwnROLHc1rD0sL~Zy6~E36HgxJ@@

	decoded, _ = CustomEncodingWithAt.DecodeString(encoded)
	fmt.Println(string(decoded))
	// Hello Golang!窗前明月光,疑是地上霜,举头望明月,低头思故乡
}