2018-06-30 00:57:05 +00:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
2020-03-16 06:51:15 +00:00
|
|
|
"crypto/sha256"
|
2018-06-30 00:57:05 +00:00
|
|
|
"fmt"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
|
|
"math/rand"
|
2018-10-07 22:38:56 +00:00
|
|
|
"time"
|
2018-06-30 00:57:05 +00:00
|
|
|
)
|
|
|
|
|
2018-09-10 22:16:23 +00:00
|
|
|
// HashPassword returns the bcrypt hash of a password string
|
2018-06-30 00:57:05 +00:00
|
|
|
func HashPassword(password string) string {
|
|
|
|
bytes, _ := bcrypt.GenerateFromPassword([]byte(password), 14)
|
|
|
|
return string(bytes)
|
|
|
|
}
|
|
|
|
|
2020-06-06 00:36:39 +00:00
|
|
|
// CheckHash returns true if the password matches with a hashed bcrypt password
|
|
|
|
func CheckHash(password, hash string) bool {
|
|
|
|
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
|
|
|
return err == nil
|
|
|
|
}
|
|
|
|
|
2018-09-10 22:16:23 +00:00
|
|
|
// NewSHA1Hash returns a random SHA1 hash based on a specific length
|
2020-03-16 06:51:15 +00:00
|
|
|
func NewSHA256Hash() string {
|
|
|
|
d := make([]byte, 10)
|
|
|
|
rand.Seed(Now().UnixNano())
|
2020-03-19 01:50:53 +00:00
|
|
|
rand.Read(d)
|
|
|
|
return fmt.Sprintf("%x", sha256.Sum256(d))
|
2018-06-30 00:57:05 +00:00
|
|
|
}
|
|
|
|
|
2020-07-15 04:26:54 +00:00
|
|
|
// NewSHA1Hash returns a random SHA1 hash based on a specific length
|
|
|
|
func Sha256Hash(val string) string {
|
|
|
|
return fmt.Sprintf("%x", sha256.Sum256([]byte(val)))
|
|
|
|
}
|
|
|
|
|
2018-06-30 00:57:05 +00:00
|
|
|
var characterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
|
|
|
|
|
|
|
|
// RandomString generates a random string of n length
|
|
|
|
func RandomString(n int) string {
|
|
|
|
b := make([]rune, n)
|
2018-10-07 22:38:56 +00:00
|
|
|
rand.Seed(time.Now().UnixNano())
|
2018-06-30 00:57:05 +00:00
|
|
|
for i := range b {
|
|
|
|
b[i] = characterRunes[rand.Intn(len(characterRunes))]
|
|
|
|
}
|
|
|
|
return string(b)
|
|
|
|
}
|