Go Cheatsheet - base64,32,58 encoding
base64,32,58 encoding
base64
Standard Encoding/Decoding
import (
"encoding/base64"
"fmt"
)
func main() {
data := []byte("test data")
b64Enc := base64.StdEncoding.EncodeToString([]byte(data))
fmt.Println("B64 Encoded:", b64Enc)
b64Dec, err := base64.StdEncoding.DecodeString(b64Enc)
if err != nil {
fmt.Println("Failed to b64 decode")
}
fmt.Println("B64 Decoded:", string(b64Dec))
}
URL Safe Encoding/Decoding
import (
"encoding/base64"
"fmt"
)
func main() {
data := []byte("test data")
b64UEnc := base64.URLEncoding.EncodeToString([]byte(data))
fmt.Println("B64 URLEncoded:", b64UEnc)
b64UDec, err := base64.URLEncoding.DecodeString(b64UEnc)
if err != nil {
fmt.Println("Failed to b64 url decode")
}
fmt.Println("B64 URLDecoded:", string(b64UDec)
}
base32
import (
"encoding/base32"
"fmt"
)
func main() {
data := []byte("test data")
b32Enc := base32.StdEncoding.EncodeToString([]byte(data))
fmt.Println("B32 Encoded:", b32Enc)
b32Dec, err := base32.StdEncoding.DecodeString(b32Enc)
if err != nil {
fmt.Println("Failed to b32 decode")
}
fmt.Println("B32 Decoded:", string(b32Dec))
}
base58
Need to install base58
package:
$ go get github.com/mr-tron/base58
Code:
import (
"fmt"
"github.com/mr-tron/base58"
)
func main() {
data := []byte("test data")
b58Enc := base58.Encode(data)
fmt.Println("B58 Encoded:", b58Enc)
b58Dec, err := base58.Decode(b58Enc)
if err != nil {
fmt.Println("Failed to b58 decode")
}
fmt.Println("B58 Decoded:", string(b58Dec))
}