见代码:
package main
import (
"crypto/md5"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"fmt"
"io"
)
func main() {
var str string = "hello world"
// md5
// 1.md5V1
h1 := md5.New()
h1.Write([]byte(str))
md5V1 := hex.EncodeToString(h1.Sum(nil))
fmt.Printf("md5V1: %s\n", md5V1)
// 2.md5V2
h2 := md5.Sum([]byte(str))
md5V2 := fmt.Sprintf("%x", h2)
fmt.Printf("md5V2: %s\n", md5V2)
// 3.md5V3
h3 := md5.New()
io.WriteString(h3, str)
md5V3 := fmt.Sprintf("%x", h3.Sum(nil))
fmt.Printf("md5V2: %s\n", md5V3)
/*
md5V1: 5eb63bbbe01eeed093cb22bb8f5acdc3
md5V2: 5eb63bbbe01eeed093cb22bb8f5acdc3
md5V2: 5eb63bbbe01eeed093cb22bb8f5acdc3
*/
// sha256
// 1.sha256V1
s1 := sha256.New()
s1.Write([]byte(str))
sha256v1 := hex.EncodeToString(s1.Sum(nil))
fmt.Printf("sha256v1: %s\n", sha256v1)
// 2.sha256V2
s2 := sha256.Sum256([]byte(str))
sha256V2 := fmt.Sprintf("%x", s2)
fmt.Printf("sha256v2: %s\n", sha256V2)
// 3.sha256V3
s3 := sha256.New()
s3.Write([]byte(str))
sha256V3 := fmt.Sprintf("%x", s3.Sum(nil))
fmt.Printf("sha256v3: %s\n", sha256V3)
/*
sha256v1: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
sha256v2: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
sha256v3: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
*/
// base64
// encode
encodeStr := base64.StdEncoding.EncodeToString([]byte(str))
fmt.Printf("base64 encode: %s\n", encodeStr)
// decode
decodeStr, err := base64.StdEncoding.DecodeString(encodeStr)
if err != nil {
fmt.Println(err)
}
fmt.Printf("base64 decode: %s\n", decodeStr)
/*
base64 encode: aGVsbG8gd29ybGQ=
base64 decode: hello world
*/
// uriencode -> 把“/”换成“_”,把“+”换成“-”
uriEncode := base64.URLEncoding.EncodeToString([]byte(str))
fmt.Printf("base64 uriencode: %s\n", uriEncode)
uriDecode, err := base64.URLEncoding.DecodeString(uriEncode)
if err != nil {
fmt.Println(err)
}
fmt.Printf("base64 uridecode: %s\n", uriDecode)
/*
base64 uriencode: aGVsbG8gd29ybGQ=
base64 uridecode: hello world
*/
}