diff --git a/cmd/apg/apg.go b/cmd/apg/apg.go index 9a0666b..05cddd2 100644 --- a/cmd/apg/apg.go +++ b/cmd/apg/apg.go @@ -23,6 +23,7 @@ func main() { flag.BoolVar(&sp, "S", false, "") flag.BoolVar(&co, "C", false, "") flag.BoolVar(&hr, "H", false, "") + flag.Int64Var(&c.FixedLength, "f", 0, "") flag.Int64Var(&c.MinLength, "m", c.MinLength, "") flag.Int64Var(&c.MaxLength, "x", c.MaxLength, "") flag.StringVar(&ms, "M", "", "") @@ -56,19 +57,16 @@ func main() { if ms != "" { c.Mode = apg.ModesFromFlags(ms) } - for _, m := range []apg.Mode{apg.ModeHumanReadable, apg.ModeLowerCase, apg.ModeNumber, apg.ModeSpecial, apg.ModeUpperCase} { - fmt.Printf("%s: %t\n", m, apg.MaskHasMode(c.Mode, m)) - } - /* - g := apg.New(c) - rb, err := g.RandomBytes(c.MinLength) - if err != nil { - fmt.Println("ERROR", err) - os.Exit(1) - } - fmt.Printf("Random: %#v\n", rb) - */ + // Generate the password based on the given flags + g := apg.New(c) + for i := int64(0); i < c.NumberPass; i++ { + pl, err := g.GetPasswordLength() + if err != nil { + _, _ = fmt.Fprintf(os.Stderr, "Error during password generation: %s\n", err) + } + fmt.Printf("PW length: %d\n", pl) + } } // usage is used by the flag package to display the CLI usage message @@ -86,6 +84,7 @@ Options: - 1: random password generation according to password modes/flags -m LENGTH Minimum length of the password to be generated (Default: 12) -x LENGTH Maximum length of the password to be generated (Default: 20) + -f LENGTH Fixed length of the password to be generated (Ignores -m and -x) -n NUMBER Amount of password to be generated (Default: 6) -E CHARS List of characters to be excluded in the generated password -M [LUNSHClunshc] New style password parameters diff --git a/config.go b/config.go index 9a0e405..ef2378c 100644 --- a/config.go +++ b/config.go @@ -17,6 +17,9 @@ const ( type Config struct { // Algo Algorithm Algorithm + // FixedLength sets a fixed length for generated passwords and ignores + // the MinLength and MaxLength values + FixedLength int64 // MaxLength sets the maximum length for a generated password MaxLength int64 // MinLength sets the minimum length for a generated password diff --git a/random.go b/random.go index 12f792c..5b653d7 100644 --- a/random.go +++ b/random.go @@ -106,3 +106,26 @@ func (g *Generator) CoinFlip() int64 { func (g *Generator) CoinFlipBool() bool { return g.CoinFlip() == 1 } + +// GetPasswordLength returns the password length based on the given config +// parameters +func (g *Generator) GetPasswordLength() (int64, error) { + if g.config.FixedLength > 0 { + return g.config.FixedLength, nil + } + mil := g.config.MinLength + mal := g.config.MaxLength + if mil > mal { + mal = mil + } + diff := mal - mil + 1 + ra, err := g.RandNum(diff) + if err != nil { + return 0, fmt.Errorf("failed to calculate password length: %w", err) + } + l := mil + ra + if l <= 0 { + return 1, nil + } + return l, nil +}