Last active
November 14, 2019 16:06
-
-
Save lmas/7144d24b277fb359cbd353dc50ba07d5 to your computer and use it in GitHub Desktop.
Generate random, hex encoded tokens
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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