git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/tools/password/main.go (about)

     1  package main
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"os"
     7  
     8  	"git.sr.ht/~pingoo/stdx/cobra"
     9  	"git.sr.ht/~pingoo/stdx/crypto"
    10  )
    11  
    12  const (
    13  	defaultPasswordLength = 128
    14  	version               = "1.0.0"
    15  )
    16  
    17  const (
    18  	// LowerLetters is the list of lowercase letters.
    19  	LowerLetters = "abcdefghijklmnopqrstuvwxyz"
    20  
    21  	// UpperLetters is the list of uppercase letters.
    22  	UpperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    23  
    24  	// Digits is the list of permitted digits.
    25  	Digits = "0123456789"
    26  
    27  	// Symbols is the list of symbols.
    28  	Symbols = "~!@#$%^&*()_+`-={}|[]\\:\"<>?,./"
    29  
    30  	All = LowerLetters + UpperLetters + Digits + Symbols
    31  )
    32  
    33  var (
    34  	passwordLength uint64
    35  )
    36  
    37  func init() {
    38  	rootCmd.Flags().Uint64VarP(&passwordLength, "length", "n", defaultPasswordLength, "Password length (default: 128, min: 8, max: 4096)")
    39  }
    40  
    41  func main() {
    42  	err := rootCmd.Execute()
    43  	if err != nil {
    44  		fmt.Fprintln(os.Stdout, err.Error())
    45  		os.Exit(1)
    46  	}
    47  }
    48  
    49  var rootCmd = &cobra.Command{
    50  	Use:           "password",
    51  	Short:         "Generate secure passwords",
    52  	Version:       version,
    53  	SilenceUsage:  true,
    54  	SilenceErrors: true,
    55  	RunE: func(cmd *cobra.Command, args []string) (err error) {
    56  		if passwordLength < 8 {
    57  			err = errors.New("Password cannot be shorter than 8 characters")
    58  			return
    59  		} else if passwordLength > 4096 {
    60  			err = errors.New("Password cannot be longer than 4096 characters")
    61  			return
    62  		}
    63  
    64  		password, err := crypto.RandAlphabet([]byte(All), passwordLength)
    65  		if err != nil {
    66  			return
    67  		}
    68  		fmt.Println(string(password))
    69  
    70  		return
    71  	},
    72  }