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_test.go 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright (c) 2018 Shivaram Lingamneni <slingamn@cs.stanford.edu>
  2. // released under the MIT license
  3. package utils
  4. import (
  5. "testing"
  6. )
  7. const (
  8. storedToken = "1e82d113a59a874cccf82063ec603221"
  9. badToken = "1e82d113a59a874cccf82063ec603222"
  10. shortToken = "1e82d113a59a874cccf82063ec60322"
  11. longToken = "1e82d113a59a874cccf82063ec6032211"
  12. )
  13. func TestGenerateSecretToken(t *testing.T) {
  14. token := GenerateSecretToken()
  15. if len(token) != SecretTokenLength {
  16. t.Errorf("bad token: %v", token)
  17. }
  18. }
  19. func TestTokenCompare(t *testing.T) {
  20. if !SecretTokensMatch(storedToken, storedToken) {
  21. t.Error("matching tokens must match")
  22. }
  23. if SecretTokensMatch(storedToken, badToken) {
  24. t.Error("non-matching tokens must not match")
  25. }
  26. if SecretTokensMatch(storedToken, shortToken) {
  27. t.Error("non-matching tokens must not match")
  28. }
  29. if SecretTokensMatch(storedToken, longToken) {
  30. t.Error("non-matching tokens must not match")
  31. }
  32. if SecretTokensMatch("", "") {
  33. t.Error("the empty token should not match anything")
  34. }
  35. if SecretTokensMatch("", storedToken) {
  36. t.Error("the empty token should not match anything")
  37. }
  38. }
  39. func TestMunging(t *testing.T) {
  40. count := 131072
  41. set := make(map[string]bool)
  42. var token string
  43. for i := 0; i < count; i++ {
  44. token = GenerateSecretToken()
  45. set[token] = true
  46. }
  47. // all tokens generated thus far should be unique
  48. assertEqual(len(set), count, t)
  49. // iteratively munge the last generated token an additional `count` times
  50. mungedToken := token
  51. for i := 0; i < count; i++ {
  52. mungedToken = MungeSecretToken(mungedToken)
  53. assertEqual(len(mungedToken), len(token), t)
  54. set[mungedToken] = true
  55. }
  56. // munged tokens should not collide with generated tokens, or each other
  57. assertEqual(len(set), count*2, t)
  58. }
  59. func BenchmarkGenerateSecretToken(b *testing.B) {
  60. for i := 0; i < b.N; i++ {
  61. GenerateSecretToken()
  62. }
  63. }
  64. func BenchmarkMungeSecretToken(b *testing.B) {
  65. t := GenerateSecretToken()
  66. for i := 0; i < b.N; i++ {
  67. t = MungeSecretToken(t)
  68. }
  69. }