Skip to content

Instantly share code, notes, and snippets.

@nicklaw5
Last active December 19, 2022 10:25
Show Gist options
  • Save nicklaw5/9d2d76b04d345152364d9b8cb4b554e9 to your computer and use it in GitHub Desktop.
Save nicklaw5/9d2d76b04d345152364d9b8cb4b554e9 to your computer and use it in GitHub Desktop.
Golang - Generate random SHA1 hash
// Source: https://stackoverflow.com/questions/12321133/golang-random-number-generator-how-to-seed-properly
package main
import (
"crypto/sha1"
"fmt"
"math/rand"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func main() {
hash := NewSHA1Hash()
fmt.Println(hash)
}
// NewSHA1Hash generates a new SHA1 hash based on
// a random number of characters.
func NewSHA1Hash(n ...int) string {
noRandomCharacters := 32
if len(n) > 0 {
noRandomCharacters = n[0]
}
randString := RandomString(noRandomCharacters)
hash := sha1.New()
hash.Write([]byte(randString))
bs := hash.Sum(nil)
return fmt.Sprintf("%x", bs)
}
var characterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
// RandomString generates a random string of n length
func RandomString(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = characterRunes[rand.Intn(len(characterRunes))]
}
return string(b)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment