/** * AltGit - altgit * * This file is licensed under the Affero General Public License version 3 or * later. See the COPYING file. * * @author Paolo Lulli * @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) }