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.

bcrypt_test.go 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright (c) 2018 Shivaram Lingamneni
  2. // released under the MIT license
  3. package passwd
  4. import (
  5. "testing"
  6. )
  7. func TestBasic(t *testing.T) {
  8. hash, err := GenerateFromPassword([]byte("this is my passphrase"), DefaultCost)
  9. if err != nil || len(hash) != 60 {
  10. t.Errorf("bad password hash output: error %s, output %s, len %d", err, hash, len(hash))
  11. }
  12. if CompareHashAndPassword(hash, []byte("this is my passphrase")) != nil {
  13. t.Errorf("hash comparison failed unexpectedly")
  14. }
  15. if CompareHashAndPassword(hash, []byte("this is not my passphrase")) == nil {
  16. t.Errorf("hash comparison succeeded unexpectedly")
  17. }
  18. }
  19. func TestVector(t *testing.T) {
  20. // sanity check for persisted hashes
  21. if CompareHashAndPassword(
  22. []byte("$2a$12$sJokyLJ5px3Nb51DEDhsQ.wh8nfwEYuMbVYrpqO5v9Ylyj0YyVWj."),
  23. []byte("this is my passphrase"),
  24. ) != nil {
  25. t.Errorf("hash comparison failed unexpectedly")
  26. }
  27. }
  28. func TestLongPassphrases(t *testing.T) {
  29. longPassphrase := make([]byte, 168)
  30. for i := range longPassphrase {
  31. longPassphrase[i] = 'a'
  32. }
  33. hash, err := GenerateFromPassword(longPassphrase, DefaultCost)
  34. if err != nil {
  35. t.Errorf("bad password hash output: error %s", err)
  36. }
  37. if CompareHashAndPassword(hash, longPassphrase) != nil {
  38. t.Errorf("hash comparison failed unexpectedly")
  39. }
  40. // change a byte of the passphrase beyond the normal 80-character
  41. // bcrypt truncation boundary:
  42. longPassphrase[150] = 'b'
  43. if CompareHashAndPassword(hash, longPassphrase) == nil {
  44. t.Errorf("hash comparison succeeded unexpectedly")
  45. }
  46. }
  47. // this could be useful for tuning the cost parameter on specific hardware
  48. func BenchmarkComparisons(b *testing.B) {
  49. pass := []byte("passphrase for benchmarking")
  50. hash, err := GenerateFromPassword(pass, DefaultCost)
  51. if err != nil {
  52. b.Errorf("bad output")
  53. }
  54. b.ResetTimer()
  55. for i := 0; i < b.N; i++ {
  56. CompareHashAndPassword(hash, pass)
  57. }
  58. }