package tool
import (
"crypto/md5"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"fmt"
"io"
)
func EncoderSha256(data string) string {
h := sha256.New()
h.Write([]byte(data))
sum := h.Sum(nil)
//由于是十六进制表示,因此需要转换
s := hex.EncodeToString(sum)
return string(s)
}
func Md5(data string) string {
w := md5.New()
io.WriteString(w, data)
bydate := w.Sum(nil)
result := fmt.Sprintf("%x", bydate)
return result
}
func Base64Encode(data string) string {
return base64.StdEncoding.EncodeToString([]byte(data))
}
func Base64Decode(data string) ([]byte, error) {
return base64.StdEncoding.DecodeString(data)
}
用户名密码加密+加时间戳盐
func main() {
h := sha256.New()
_, _ = h.Write([]byte("password"))
// 加盐
salt := 1639992878
_, _ = io.WriteString(h, strconv.Itoa(salt))
sum := h.Sum(nil)
fmt.Println(sum)
s := hex.EncodeToString(sum)
fmt.Println(s)
a := "4dcdee6fe15be49c956fee902c0a6e2a82f85bfea9c8606f5448114857ad34fe"
fmt.Println(a == s)
}
md5加密+加盐封装
const (
RANDOM_STR = "qwertyuioplkjhgfdsazxcvbnm123456789.+-*/0=_-)(*&^%$#@!~"
)
//小写的
func Md5Encode(data string) string{
h := md5.New()
h.Write([]byte(data)) // 需要加密的字符串为 123456
cipherStr := h.Sum(nil)
return hex.EncodeToString(cipherStr)
}
//大写
func MD5Encode(data string) string{
return strings.ToUpper(Md5Encode(data))
}
func ValidatePasswd(plainpwd,salt,passwd string) bool{
return Md5Encode(plainpwd+salt)==passwd
}
func MakePasswd(plainpwd,salt string) string{
return Md5Encode(plainpwd+salt)
}
func GenerateSalt(length int) (str string) {
// 生成指定位数的随机字符串
rand.Seed(time.Now().UnixNano()) // 随机种子
for i := 0; i < length; i++ {
ii := rand.Intn(len(RANDOM_STR))
str += string(RANDOM_STR[ii])
}
return
}