Skip to content

Commit ee0f001

Browse files
Alexander Sheikoruiztulio
authored andcommitted
Add VerifyPassword from foomo#9
1 parent 64065f8 commit ee0f001

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

htpasswd.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ import (
88
"io/ioutil"
99
"os"
1010
"strings"
11+
12+
"github.com/GehirnInc/crypt/apr1_crypt"
13+
"golang.org/x/crypto/bcrypt"
1114
)
1215

1316
// HashedPasswords name => hash
@@ -25,6 +28,13 @@ const (
2528
HashSHA = "sha"
2629
)
2730

31+
// HashAlgorithms is a list of supported hashes
32+
var HashAlgorithms = []HashAlgorithm{
33+
HashAPR1,
34+
HashBCrypt,
35+
HashSHA,
36+
}
37+
2838
const (
2939
// PasswordSeparator separates passwords from hashes
3040
PasswordSeparator = ":"
@@ -75,6 +85,25 @@ func (hp HashedPasswords) SetPassword(name, password string, hashAlgorithm HashA
7585
return nil
7686
}
7787

88+
// VerifyPassword verify a password for a user with a hashing algo
89+
func (hp HashedPasswords) VerifyPassword(name, password string, hashAlgorithm HashAlgorithm) bool {
90+
if len(password) == 0 {
91+
return false
92+
}
93+
switch hashAlgorithm {
94+
case HashAPR1:
95+
err := apr1_crypt.New().Verify(hp[name], []byte(password))
96+
return err == nil
97+
case HashSHA:
98+
return "{SHA}"+hashSha(password) == hp[name]
99+
case HashBCrypt:
100+
err := bcrypt.CompareHashAndPassword([]byte(hp[name]), []byte(password))
101+
return err == nil
102+
default:
103+
return false
104+
}
105+
}
106+
78107
// ParseHtpasswdFile load a htpasswd file
79108
func ParseHtpasswdFile(file string) (passwords HashedPasswords, err error) {
80109
htpasswdBytes, err := ioutil.ReadFile(file)

htpasswd_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,3 +135,12 @@ func TestHashing(t *testing.T) {
135135
}
136136
}
137137
}
138+
139+
func TestVerify(t *testing.T) {
140+
testHashes := getHashedPasswords()
141+
for _, algo := range HashAlgorithms {
142+
if !testHashes.VerifyPassword(string(algo), string(algo), algo) {
143+
t.Error(algo, testHashes[string(algo)])
144+
}
145+
}
146+
}

0 commit comments

Comments
 (0)