-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashing.go
47 lines (40 loc) · 1.39 KB
/
hashing.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package permissions
import (
"crypto/sha256"
"crypto/subtle"
"golang.org/x/crypto/bcrypt"
"io"
)
// Hash the password with sha256 (the username is needed for salting)
func hashSha256(cookieSecret, username, password string) []byte {
hasher := sha256.New()
// Use the cookie secret as additional salt
io.WriteString(hasher, password+cookieSecret+username)
return hasher.Sum(nil)
}
// Hash the password with bcrypt
func hashBcrypt(password string) []byte {
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
panic("Permissions: bcrypt password hashing unsuccessful")
}
return hash
}
// Check if a given password(+username) is correct, for a given sha256 hash
func correctSha256(hash []byte, cookieSecret, username, password string) bool {
comparisonHash := hashSha256(cookieSecret, username, password)
// check that the lengths are equal before calling ConstantTimeCompare
if len(hash) != len(comparisonHash) {
return false
}
// helps prevent timing attacks
return subtle.ConstantTimeCompare(hash, comparisonHash) == 1
}
// Check if a given password is correct, for a given bcrypt hash
func correctBcrypt(hash []byte, password string) bool {
return bcrypt.CompareHashAndPassword(hash, []byte(password)) == nil
}
// Check if the given hash is sha256 (when the alternative is only bcrypt)
func isSha256(hash []byte) bool {
return len(hash) == 32
}