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.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 TestLongPassphrases(t *testing.T) {
  20. longPassphrase := make([]byte, 168)
  21. for i := range longPassphrase {
  22. longPassphrase[i] = 'a'
  23. }
  24. hash, err := GenerateFromPassword(longPassphrase, DefaultCost)
  25. if err != nil {
  26. t.Errorf("bad password hash output: error %s", err)
  27. }
  28. if CompareHashAndPassword(hash, longPassphrase) != nil {
  29. t.Errorf("hash comparison failed unexpectedly")
  30. }
  31. // change a byte of the passphrase beyond the normal 80-character
  32. // bcrypt truncation boundary:
  33. longPassphrase[150] = 'b'
  34. if CompareHashAndPassword(hash, longPassphrase) == nil {
  35. t.Errorf("hash comparison succeeded unexpectedly")
  36. }
  37. }
  38. // this could be useful for tuning the cost parameter on specific hardware
  39. func BenchmarkComparisons(b *testing.B) {
  40. pass := []byte("passphrase for benchmarking")
  41. hash, err := GenerateFromPassword(pass, DefaultCost)
  42. if err != nil {
  43. b.Errorf("bad output")
  44. }
  45. b.ResetTimer()
  46. for i := 0; i < b.N; i++ {
  47. CompareHashAndPassword(hash, pass)
  48. }
  49. }