Skip to content

Instantly share code, notes, and snippets.

@nqthqn
Created May 26, 2020 21:43
Show Gist options
  • Save nqthqn/204329da36882f7a7abb0fb5e8149b9e to your computer and use it in GitHub Desktop.
Save nqthqn/204329da36882f7a7abb0fb5e8149b9e to your computer and use it in GitHub Desktop.
Generate random passwords
package main
import (
"flag"
"fmt"
"math/rand"
"os"
"strings"
"time"
)
func main() {
c := flag.String("custom", "", "User-provided string")
d := flag.Bool("decimal", false, "Digits 0 - 9")
lc := flag.Bool("lowercase", false, "ASCII lowercase characters")
uc := flag.Bool("uppercase", false, "ASCII uppercase characters")
p := flag.Bool("punctuation", false, "All ASCII punctuation characters")
s := flag.Bool("special", false, "ASCII punctuation without quotes or backslashes")
l := flag.Int("length", 10, "Length of string")
flag.Parse()
if *p && *s {
fmt.Println("Error: Special and Punctuation cannot be combined.")
flag.PrintDefaults()
os.Exit(1)
}
special := "!#$%&()*+,-./:;<=>?@[]^_`{|}~"
// default pool to use if no args
pool := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + special
// if an arg is provided build custom pool
if !(*c == "" && !*d && !*lc && !*uc && !*p && !*s) {
pool = ""
pool += *c
if *d {
pool += "0123456789"
}
if *lc {
pool += "abcdefghijklmnopqrstuvwxyz"
}
if *uc {
pool += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
}
if *p {
pool += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
}
if *s {
pool += special
}
}
// https://yourbasic.org/golang/generate-random-string/
rand.Seed(time.Now().UnixNano())
chars := []rune(pool)
var b strings.Builder
for i := 0; i < *l; i++ {
b.WriteRune(chars[rand.Intn(len(chars))])
}
str := b.String()
fmt.Print(str)
}
@nqthqn
Copy link
Author

nqthqn commented May 26, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment