Skip to content

Instantly share code, notes, and snippets.

@lmas
Last active November 14, 2019 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lmas/7144d24b277fb359cbd353dc50ba07d5 to your computer and use it in GitHub Desktop.
Save lmas/7144d24b277fb359cbd353dc50ba07d5 to your computer and use it in GitHub Desktop.
Generate random, hex encoded tokens
package main
import (
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"fmt"
"time"
)
const (
bytesTime int = 8 // uint64 = 8 bytes long
bytesRand int = 56
// 8 + 56 = 64 bytes in total
)
func newToken(ts time.Time) string {
buf := make([]byte, bytesTime+bytesRand)
t := uint64(ts.UnixNano())
binary.BigEndian.PutUint64(buf[:bytesTime], t)
_, err := rand.Read(buf[bytesTime:])
if err != nil {
panic(err)
}
h := sha256.New()
h.Write(buf)
return hex.EncodeToString(h.Sum(nil))
}
func main() {
t := time.Now()
for i := 0; i < 10; i++ {
t = t.Add(time.Duration(i) * time.Second)
fmt.Println(newToken(t))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment