tokens.go 790 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package secrets
  3. import (
  4. "crypto/rand"
  5. "encoding/base64"
  6. "encoding/hex"
  7. "fmt"
  8. )
  9. var _ = fmt.Print
  10. const DEFAULT_NUM_OF_BYTES_FOR_TOKEN = 32
  11. func TokenBytes(nbytes ...int) ([]byte, error) {
  12. if len(nbytes) == 0 {
  13. nbytes = []int{DEFAULT_NUM_OF_BYTES_FOR_TOKEN}
  14. }
  15. buf := make([]byte, nbytes[0])
  16. _, err := rand.Read(buf)
  17. if err != nil {
  18. return nil, err
  19. }
  20. return buf, nil
  21. }
  22. func TokenHex(nbytes ...int) (string, error) {
  23. b, err := TokenBytes(nbytes...)
  24. if err != nil {
  25. return "", err
  26. }
  27. return hex.EncodeToString(b), nil
  28. }
  29. func TokenBase64(nbytes ...int) (string, error) {
  30. b, err := TokenBytes(nbytes...)
  31. if err != nil {
  32. return "", err
  33. }
  34. return base64.StdEncoding.EncodeToString(b), nil
  35. }