salt.go 907 B

12345678910111213141516171819202122232425262728293031
  1. package crypt
  2. import (
  3. "crypto/rand"
  4. "encoding/base64"
  5. )
  6. // GenerateRandomBytes returns securely generated random bytes.
  7. // It will return an error if the system's secure random
  8. // number generator fails to function correctly, in which
  9. // case the caller should not continue.
  10. func GenerateRandomBytes(n int) ([]byte, error) {
  11. b := make([]byte, n)
  12. _, err := rand.Read(b)
  13. // Note that err == nil only if we read len(b) bytes.
  14. if err != nil {
  15. return nil, err
  16. }
  17. return b, nil
  18. }
  19. // GenerateRandomString returns a URL-safe, base64 encoded
  20. // securely generated random string.
  21. // It will return an error if the system's secure random
  22. // number generator fails to function correctly, in which
  23. // case the caller should not continue.
  24. func GenerateRandomString(s int) (string, error) {
  25. b, err := GenerateRandomBytes(s)
  26. return base64.URLEncoding.EncodeToString(b), err
  27. }