// passgen <thinkofher, github.com/thinkofher>
//
// Go is truth.
//
// Building and usage:
//
// $ go build -o passgen .
// $ ./passgen 32
// OHa0)j3:MijW%u)j1g{{siz/'NTx=QMv
// $ ./passgen 16
// %(k9pD+]52dPU/-
//
package main
import (
"fmt"
"math/rand"
"os"
"strconv"
"time"
)
// You have to start with something
// clever, right? No? Whatever.
const MIN = int('!')
const MAX = int('}')
func main() {
// First argument is always program that you run.
// So if user provides less than two arguments, that means
// he/she's providing zero arguments, that we can call useful.
if len(os.Args) < 2 {
fmt.Fprintf(os.Stderr, "You have to provide password length!")
// That's old unix tradition.
// Things gone wrong? Return 1 and forget.
os.Exit(1)
}
// Convert first (not counting program name) argument to integer.
passLen, err := strconv.Atoi(os.Args[1])
if err != nil {
// Error occurs! That means user had tried to trick us
// and write something stupid like 'foobar' instead of
// giving us sweet like poney-honey password length as integer
// number.
fmt.Fprintf(os.Stderr, "%s is not a numerical value!", os.Args[1])
os.Exit(1)
}
if passLen < 0 {
// You thought that I missed that detail?
// I must admit, you're really smart, but not
// smarter than my password generator!
fmt.Fprintf(os.Stderr, "Password length can not be negative number.")
os.Exit(1)
}
// Do you remember that? I bet you do.
// Namespaces are good. Don't fight them!
// They will never harm you if you'll treat them
// with due respect.
rand.Seed(time.Now().UnixNano())
// That's something new.
result := make([]byte, passLen)
// And finally.
for i := range result {
result[i] = byte(rand.Intn(MAX-MIN) + MIN)
}
// We're home.
fmt.Fprintf(os.Stdin, "%s", string(result))
// Of course don't use that stupid password.
// Computers doesn't give a damn about how
// funny are bytes in your password, as long
// as you have many of them.
}
click to show comments