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.

crypto.go 891B

123456789101112131415161718192021222324252627282930
  1. // Copyright (c) 2018 Shivaram Lingamneni <slingamn@cs.stanford.edu>
  2. // released under the MIT license
  3. package utils
  4. import (
  5. "crypto/rand"
  6. "crypto/subtle"
  7. "encoding/hex"
  8. )
  9. // generate a secret token that cannot be brute-forced via online attacks
  10. func GenerateSecretToken() string {
  11. // 128 bits of entropy are enough to resist any online attack:
  12. var buf [16]byte
  13. rand.Read(buf[:])
  14. // 32 ASCII characters, should be fine for most purposes
  15. return hex.EncodeToString(buf[:])
  16. }
  17. // securely check if a supplied token matches a stored token
  18. func SecretTokensMatch(storedToken string, suppliedToken string) bool {
  19. // XXX fix a potential gotcha: if the stored token is uninitialized,
  20. // then nothing should match it, not even supplying an empty token.
  21. if len(storedToken) == 0 {
  22. return false
  23. }
  24. return subtle.ConstantTimeCompare([]byte(storedToken), []byte(suppliedToken)) == 1
  25. }