crypto_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package crypto
  2. import (
  3. "strings"
  4. "testing"
  5. )
  6. func TestHashPasswordAsBcrypt_RoundTrip(t *testing.T) {
  7. password := "correct horse battery staple"
  8. hash, err := HashPasswordAsBcrypt(password)
  9. if err != nil {
  10. t.Fatalf("HashPasswordAsBcrypt returned error: %v", err)
  11. }
  12. if hash == "" {
  13. t.Fatal("expected non-empty hash")
  14. }
  15. if hash == password {
  16. t.Fatal("hash must not equal the plaintext password")
  17. }
  18. if !strings.HasPrefix(hash, "$2") {
  19. t.Fatalf("expected bcrypt prefix $2..., got %q", hash[:min(4, len(hash))])
  20. }
  21. if !CheckPasswordHash(hash, password) {
  22. t.Fatal("CheckPasswordHash returned false for the matching password")
  23. }
  24. }
  25. func TestCheckPasswordHash_WrongPassword(t *testing.T) {
  26. hash, err := HashPasswordAsBcrypt("right-password")
  27. if err != nil {
  28. t.Fatalf("HashPasswordAsBcrypt returned error: %v", err)
  29. }
  30. if CheckPasswordHash(hash, "wrong-password") {
  31. t.Fatal("CheckPasswordHash returned true for a wrong password")
  32. }
  33. if CheckPasswordHash(hash, "") {
  34. t.Fatal("CheckPasswordHash returned true for an empty password")
  35. }
  36. }
  37. func TestCheckPasswordHash_InvalidHash(t *testing.T) {
  38. if CheckPasswordHash("", "anything") {
  39. t.Fatal("empty hash must not validate")
  40. }
  41. if CheckPasswordHash("not-a-bcrypt-hash", "anything") {
  42. t.Fatal("malformed hash must not validate")
  43. }
  44. }
  45. func TestHashPasswordAsBcrypt_DifferentHashesForSamePassword(t *testing.T) {
  46. password := "same-password"
  47. h1, err := HashPasswordAsBcrypt(password)
  48. if err != nil {
  49. t.Fatalf("first hash failed: %v", err)
  50. }
  51. h2, err := HashPasswordAsBcrypt(password)
  52. if err != nil {
  53. t.Fatalf("second hash failed: %v", err)
  54. }
  55. if h1 == h2 {
  56. t.Fatal("expected bcrypt to produce different hashes (random salt) for the same password")
  57. }
  58. if !CheckPasswordHash(h1, password) || !CheckPasswordHash(h2, password) {
  59. t.Fatal("both hashes should still validate the original password")
  60. }
  61. }