1
Fork 0
mirror of https://github.com/jech/galene.git synced 2024-11-25 18:15:57 +01:00
galene/galene-password-generator/galene-password-generator.go

108 lines
2.3 KiB
Go
Raw Normal View History

2020-11-29 14:26:42 +01:00
package main
import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
2020-11-29 14:26:42 +01:00
"log"
"os"
"strings"
2020-11-29 14:26:42 +01:00
"golang.org/x/crypto/bcrypt"
2020-11-29 14:26:42 +01:00
"golang.org/x/crypto/pbkdf2"
2020-12-19 17:37:48 +01:00
"github.com/jech/galene/group"
2020-11-29 14:26:42 +01:00
)
func main() {
var algorithm string
2020-11-29 14:26:42 +01:00
var iterations int
var cost int
2020-11-29 14:26:42 +01:00
var length int
var saltLen int
var username string
var permissions string
flag.StringVar(&username, "user", "",
"generate entry for given `username`")
flag.StringVar(&permissions, "permissions", "present",
"`permissions` for user entry")
flag.StringVar(&algorithm, "hash", "pbkdf2",
"hashing `algorithm`")
flag.IntVar(&iterations, "iterations", 4096,
"`number` of iterations (pbkdf2)")
flag.IntVar(&cost, "cost", bcrypt.DefaultCost,
"`cost` (bcrypt)")
flag.IntVar(&length, "key", 32, "key `length` (pbkdf2)")
flag.IntVar(&saltLen, "salt", 8, "salt `length` (pbkdf2)")
2020-11-29 14:26:42 +01:00
flag.Parse()
if len(flag.Args()) == 0 {
fmt.Fprintf(
flag.CommandLine.Output(),
"Usage: %s [option...] password...\n",
os.Args[0])
flag.PrintDefaults()
2020-11-29 14:26:42 +01:00
os.Exit(2)
}
salt := make([]byte, saltLen)
for _, pw := range flag.Args() {
_, err := rand.Read(salt)
if err != nil {
log.Fatalf("Salt: %v", err)
}
var p group.Password
if strings.EqualFold(algorithm, "pbkdf2") {
key := pbkdf2.Key(
[]byte(pw), salt, iterations, length, sha256.New,
)
encoded := hex.EncodeToString(key)
p = group.Password{
Type: "pbkdf2",
Hash: "sha-256",
Key: &encoded,
Salt: hex.EncodeToString(salt),
Iterations: iterations,
}
} else if strings.EqualFold(algorithm, "bcrypt") {
key, err := bcrypt.GenerateFromPassword(
[]byte(pw), cost,
)
if err != nil {
log.Fatalf("Couldn't hash password: %v", err)
}
2020-11-29 14:26:42 +01:00
k := string(key)
p = group.Password{
Type: "bcrypt",
Key: &k,
}
} else {
log.Fatalf("Unknown hash type %v", algorithm)
2020-11-29 14:26:42 +01:00
}
2020-11-29 14:26:42 +01:00
e := json.NewEncoder(os.Stdout)
if username != "" {
perms, err := group.NewPermissions(permissions)
if err != nil {
log.Fatalf("NewPermissions: %v", err)
}
creds := make(map[string]group.UserDescription)
creds[username] = group.UserDescription{
Password: p,
Permissions: perms,
}
err = e.Encode(creds)
} else {
err = e.Encode(p)
}
2020-11-29 14:26:42 +01:00
if err != nil {
log.Fatalf("Encode: %v", err)
}
}
}