crypto.go 685 B

123456789101112131415161718192021222324252627282930
  1. package randutil
  2. import (
  3. crand "crypto/rand"
  4. "encoding/binary"
  5. "math/big"
  6. )
  7. // GenerateCryptoRandomString generates a random string for cryptographic usage.
  8. func GenerateCryptoRandomString(n int, runes string) (string, error) {
  9. letters := []rune(runes)
  10. b := make([]rune, n)
  11. for i := range b {
  12. v, err := crand.Int(crand.Reader, big.NewInt(int64(len(letters))))
  13. if err != nil {
  14. return "", err
  15. }
  16. b[i] = letters[v.Int64()]
  17. }
  18. return string(b), nil
  19. }
  20. // CryptoUint64 returns cryptographic random uint64.
  21. func CryptoUint64() (uint64, error) {
  22. var v uint64
  23. if err := binary.Read(crand.Reader, binary.LittleEndian, &v); err != nil {
  24. return 0, err
  25. }
  26. return v, nil
  27. }