base64 是常用的、简单的字符串加密方式,下面是GoLang 实现base64 加密/解密
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package main
import (
"encoding/base64"
"fmt"
)
const (
base64Table = "123QRSTUabcdVWXYZHijKLAWDCABDstEFGuvwxyzGHIJklmnopqr234560178912"
)
var coder = base64.NewEncoding(base64Table)
func base64Encode(src []byte) []byte {
return []byte(coder.EncodeToString(src))
}
func base64Decode(src []byte) ([]byte, error) {
return coder.DecodeString(string(src))
}
func main() {
// encode
hello := "hello world"
debyte := base64Encode([]byte(hello))
fmt.Println(string(debyte))
// decode
enbyte, err := base64Decode(debyte)
if err != nil {
fmt.Println(err.Error())
}
if hello != string(enbyte) {
fmt.Println("hello is not equal to enbyte")
}
fmt.Println(string(enbyte))
}
运行输出:
1
2
ATLkBT8Fs49qBTZ=
hello world
1
2
3
4
5
6
7
8
9
msg := "Hello, 世界"
encoded := base64.StdEncoding.EncodeToString([]byte(msg))
fmt.Println(encoded)
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
fmt.Println("decode error:", err)
return
}
fmt.Println(string(decoded))
1
2
SGVsbG8sIOS4lueVjA==
Hello, 世界
本文网址: https://golangnote.com/topic/36.html 转摘请注明来源