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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
/**
* AltGit - altgit
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Paolo Lulli <kevwe.com>
* @copyright Paolo Lulli 2026
*/
package webauth
import (
"crypto/rand"
"crypto/sha1"
"encoding/hex"
"fmt"
"strings"
"golang.org/x/crypto/pbkdf2"
)
// SaltBytes is the size of the salt for PBKDF2
var SaltBytes = 16
// IterationNumber is the number of iterations to generate the key
var IterationNumber = 50000
// KeyLength is the length of the Generated Key
var KeyLength = 64
func generateSalt(SaltBytes int) []byte {
var salt = make([]byte, SaltBytes)
_, err := rand.Read(salt[:])
if err != nil {
panic(err)
}
return salt
}
// GenerateKey generates a key from the given Password
func GenerateKey(password string) string {
salt := generateSalt(SaltBytes)
k := hex.EncodeToString(pbkdf2.Key([]byte(password), salt, IterationNumber, KeyLength, sha1.New))
keyString := fmt.Sprintf("%d:%s:%s", IterationNumber, hex.EncodeToString([]byte(salt)), k)
return keyString
}
// GenerateKeyWithSalt generates a key using the given salt and password
func GenerateKeyWithSalt(salt string, password string) string {
k := hex.EncodeToString(pbkdf2.Key([]byte(password), []byte(salt), IterationNumber, KeyLength, sha1.New))
keyString := fmt.Sprintf("%d:%s:%s", IterationNumber, hex.EncodeToString([]byte(salt)), k)
return keyString
}
// CheckPassword returns true if the given password matches the given key
func CheckPassword(password string, keyEncoded string) bool {
s := strings.Split(keyEncoded, ":")
_, salt, key := s[0], s[1], s[2]
hexSalt, err := hex.DecodeString(salt)
if nil != err {
return false
}
dk := pbkdf2.Key([]byte(password), hexSalt, IterationNumber, KeyLength, sha1.New)
return (hex.EncodeToString(dk) == key)
}
|