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 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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/base32"
  8. "encoding/base64"
  9. )
  10. var (
  11. // slingamn's own private b32 alphabet, removing 1, l, o, and 0
  12. B32Encoder = base32.NewEncoding("abcdefghijkmnpqrstuvwxyz23456789").WithPadding(base32.NoPadding)
  13. )
  14. const (
  15. SecretTokenLength = 26
  16. )
  17. // generate a secret token that cannot be brute-forced via online attacks
  18. func GenerateSecretToken() string {
  19. // 128 bits of entropy are enough to resist any online attack:
  20. var buf [16]byte
  21. rand.Read(buf[:])
  22. // 26 ASCII characters, should be fine for most purposes
  23. return B32Encoder.EncodeToString(buf[:])
  24. }
  25. // "munge" a secret token to a new value. requirements:
  26. // 1. MUST be roughly as unlikely to collide with `GenerateSecretToken` outputs
  27. // as those outputs are with each other
  28. // 2. SHOULD be deterministic (motivation: if a JOIN line has msgid x,
  29. // create a deterministic msgid y for the fake HistServ PRIVMSG that "replays" it)
  30. // 3. SHOULD be in the same "namespace" as `GenerateSecretToken` outputs
  31. // (same length and character set)
  32. func MungeSecretToken(token string) (result string) {
  33. bytes, err := B32Encoder.DecodeString(token)
  34. if err != nil {
  35. // this should never happen
  36. return GenerateSecretToken()
  37. }
  38. // add 1 with carrying
  39. for i := len(bytes) - 1; 0 <= i; i -= 1 {
  40. bytes[i] += 1
  41. if bytes[i] != 0 {
  42. break
  43. } // else: overflow, carry to the next place
  44. }
  45. return B32Encoder.EncodeToString(bytes)
  46. }
  47. // securely check if a supplied token matches a stored token
  48. func SecretTokensMatch(storedToken string, suppliedToken string) bool {
  49. // XXX fix a potential gotcha: if the stored token is uninitialized,
  50. // then nothing should match it, not even supplying an empty token.
  51. if len(storedToken) == 0 {
  52. return false
  53. }
  54. return subtle.ConstantTimeCompare([]byte(storedToken), []byte(suppliedToken)) == 1
  55. }
  56. // generate a 256-bit secret key that can be written into a config file
  57. func GenerateSecretKey() string {
  58. var buf [32]byte
  59. rand.Read(buf[:])
  60. return base64.RawURLEncoding.EncodeToString(buf[:])
  61. }