Golang加密解密

前端之家收集整理的这篇文章主要介绍了Golang加密解密前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package common

import (
	"crypto/md5"
	"crypto/rand"
	"encoding/base64"
	"encoding/hex"
	"io"
	"strings"
)

const (
	//BASE64字符表,不要有重复
	base64Table        = "<>:;',./?~!@#$CDVWX%^&*ABYZabcghijklmnopqrstuvwxyz01EFGHIJKLMNOPQRSTU2345678(def)_+|{}[]9/"
	hashFunctionHeader = "zh.ife.iya"
	hashFunctionFooter = "09.O25.O20.78"
)

/**
 * 对一个字符串进行MD5加密,不可解密
 */
func GetMd5String(s string) string {
	h := md5.New()
	h.Write([]byte(s + "zhifeiya")) //使用zhifeiya名字做散列值,设定后不要变
	return hex.EncodeToString(h.Sum(nil))
}

/**
 * 获取一个Guid值
 */
func GetGuid() string {
	b := make([]byte,48)
	if _,err := io.ReadFull(rand.Reader,b); err != nil {
		return ""
	}
	return GetMd5String(base64.URLEncoding.EncodeToString(b))
}

var coder = base64.NewEncoding(base64Table)

/**
 * base64加密
 */
func Base64Encode(str string) string {
	var src []byte = []byte(hashFunctionHeader + str + hashFunctionFooter)
	return string([]byte(coder.EncodeToString(src)))
}

/**
 * base64解密
 */
func Base64Decode(str string) (string,error) {
	var src []byte = []byte(str)
	by,err := coder.DecodeString(string(src))
	return strings.Replace(strings.Replace(string(by),hashFunctionHeader,"",-1),hashFunctionFooter,err
}
原文链接:https://www.f2er.com/go/190800.html

猜你在找的Go相关文章