84 lines
1.5 KiB
Go
84 lines
1.5 KiB
Go
package utils
|
|
|
|
import (
|
|
"crypto/md5"
|
|
"crypto/sha1"
|
|
"crypto/sha256"
|
|
"crypto/sha512"
|
|
"encoding/hex"
|
|
"github.com/speps/go-hashids"
|
|
"strings"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
// salt 盐值
|
|
const salt = "CHeF6AC392"
|
|
|
|
// Md5String
|
|
func Md5String(s string, salt ...string) string {
|
|
h := md5.New()
|
|
if len(salt) > 0 {
|
|
s += strings.Join(salt, "")
|
|
}
|
|
h.Write([]byte(s))
|
|
return hex.EncodeToString(h.Sum(nil))
|
|
}
|
|
|
|
// Sha1String
|
|
func Sha1String(s string) string {
|
|
h := sha1.New()
|
|
h.Write([]byte(s))
|
|
return hex.EncodeToString(h.Sum(nil))
|
|
}
|
|
|
|
// Sha256String
|
|
func Sha256String(s string) string {
|
|
h := sha256.New()
|
|
h.Write([]byte(s))
|
|
return hex.EncodeToString(h.Sum(nil))
|
|
}
|
|
|
|
// Sha512String
|
|
func Sha512String(s string) string {
|
|
h := sha512.New()
|
|
h.Write([]byte(s))
|
|
return hex.EncodeToString(h.Sum(nil))
|
|
}
|
|
|
|
func HashString(s []byte) string {
|
|
hash, _ := bcrypt.GenerateFromPassword(s, bcrypt.DefaultCost)
|
|
return string(hash)
|
|
}
|
|
|
|
func HashCompare(src, compare []byte) bool {
|
|
return bcrypt.CompareHashAndPassword(src, compare) == nil
|
|
}
|
|
|
|
// HASHIDEncode 混淆
|
|
func HASHIDEncode(src int, minLength ...int) string {
|
|
hd := hashids.NewData()
|
|
hd.Salt = salt
|
|
hd.MinLength = 12
|
|
|
|
if len(minLength) > 0 {
|
|
hd.MinLength = minLength[0]
|
|
}
|
|
h := hashids.NewWithData(hd)
|
|
e, _ := h.Encode([]int{src})
|
|
return e
|
|
}
|
|
|
|
// HASHIDDecode 还原混淆
|
|
func HASHIDDecode(src string) int {
|
|
hd := hashids.NewData()
|
|
hd.Salt = salt
|
|
h := hashids.NewWithData(hd)
|
|
e, err := h.DecodeWithError(src)
|
|
|
|
if err != nil {
|
|
return 0
|
|
}
|
|
return e[0]
|
|
}
|