Core functionality for new aiterp.net servers
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
1.3 KiB

7 years ago
7 years ago
  1. package generate
  2. import (
  3. "crypto/rand"
  4. "encoding/binary"
  5. "encoding/hex"
  6. "strings"
  7. "time"
  8. )
  9. // ID generates a 24 character hex string from 8 bytes of current time
  10. // in ns and 4 bytes of crypto-random. In practical terms, that makes
  11. // them orderable.
  12. func ID() string {
  13. bytes := make([]byte, 12)
  14. binary.BigEndian.PutUint64(bytes, uint64(time.Now().UnixNano()))
  15. rand.Read(bytes[8:])
  16. return strings.ToLower(hex.EncodeToString(bytes))
  17. }
  18. // FriendlyID generates a human-friendly ID that has a higher uniqueness,
  19. // and a limited alphabet designed for human readability and manual copying.
  20. //
  21. // There are 7.98e+22 IDs in a 16-length ID, which means that if there are
  22. // 10,000 items, you're as likely to guess one as winning the grand prize
  23. // of the biggest lotteries around the world billions of times in a row.
  24. func FriendlyID(length int) string {
  25. const alphabet = "0123456789abcdfghjkmpqrtvxy"
  26. const alphabetLength = byte(len(alphabet))
  27. // Generate random bytes
  28. results := make([]byte, length)
  29. rand.Read(results)
  30. // Truncate it within the alphabet
  31. for i := 0; i < 16; i++ {
  32. results[i] = alphabet[results[i]%alphabetLength]
  33. }
  34. return string(results)
  35. }
  36. // SessionID generates a 48 character hex string with crypto/rand
  37. func SessionID() string {
  38. bytes := make([]byte, 24)
  39. rand.Read(bytes)
  40. return strings.ToLower(hex.EncodeToString(bytes))
  41. }