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.

35 lines
710 B

  1. package crypto
  2. import (
  3. crand "crypto/rand"
  4. "encoding/hex"
  5. "io"
  6. )
  7. // This only uses the OS's randomness
  8. func randBytes(numBytes int) []byte {
  9. b := make([]byte, numBytes)
  10. _, err := crand.Read(b)
  11. if err != nil {
  12. panic(err)
  13. }
  14. return b
  15. }
  16. // This only uses the OS's randomness
  17. func CRandBytes(numBytes int) []byte {
  18. return randBytes(numBytes)
  19. }
  20. // CRandHex returns a hex encoded string that's floor(numDigits/2) * 2 long.
  21. //
  22. // Note: CRandHex(24) gives 96 bits of randomness that
  23. // are usually strong enough for most purposes.
  24. func CRandHex(numDigits int) string {
  25. return hex.EncodeToString(CRandBytes(numDigits / 2))
  26. }
  27. // Returns a crand.Reader.
  28. func CReader() io.Reader {
  29. return crand.Reader
  30. }