prosody-password/internal/services/prosody/change_password.go

54 lines
1.2 KiB
Go

package prosody
import (
"crypto/hmac"
"crypto/sha1"
"encoding/hex"
"errors"
"fmt"
"log"
"os/exec"
"github.com/xdg-go/pbkdf2"
)
func (p *Prosody) ChangePassword(user string, currentPwd string, newPwd string) error {
acc, err := p.loadAccount(user)
if err != nil {
return fmt.Errorf("p.loadAccount %w", err)
}
storedKey, err := hashPassword(currentPwd, acc.salt, acc.iterationCount)
if err != nil {
return fmt.Errorf("hashPassword: %w", err)
}
// Compare the hashes
if storedKey != acc.storedKey {
return errors.New("password is incorrect")
}
result, err := exec.Command("/usr/bin/prosodyctl", "-c", "passwd -s 12 -scny 1").Output()
if err != nil {
return fmt.Errorf("prosodcytl: %w", err)
}
log.Println("string(result)", string(result))
return nil
}
func hashPassword(password, salt string, iterationCount int) (string, error) {
// Hash the password using the SCRAM mechanism
saltedPassword := pbkdf2.Key([]byte(password), []byte(salt), iterationCount, 20, sha1.New)
clientKey := hmacSha1(saltedPassword, []byte("Client Key"))
storedKey := sha1.Sum(clientKey)
return hex.EncodeToString(storedKey[:]), nil
}
func hmacSha1(key, data []byte) []byte {
mac := hmac.New(sha1.New, key)
mac.Write(data)
return mac.Sum(nil)
}