-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpasswordgen.go
77 lines (65 loc) · 1.83 KB
/
passwordgen.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main
import (
"crypto/rand"
"flag"
"fmt"
"log"
"strings"
)
const (
lowerChars = "abcdefghijklmnopqrstuvwxyz"
upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numberChars = "0123456789"
symbolChars = "!@#$%^&*()-_=+[]{}|;:,.<>?/`~"
)
func randomInt(max int) (int, error) {
if max <= 0 {
return 0, fmt.Errorf("Invalid maximum value")
}
b := make([]byte, 1)
if _, err := rand.Read(b); err != nil {
return 0, fmt.Errorf("Error generating random number: %v", err)
}
randomNumber := int(b[0]) % max
return randomNumber, nil
}
func generatePassword(length int, useUpper, useNumbers, useSymbols bool) (string, error) {
if length < 1 {
return "", fmt.Errorf("password length must be greater than 0")
}
var charSet strings.Builder
charSet.WriteString(lowerChars)
if useUpper {
charSet.WriteString(upperChars)
}
if useNumbers {
charSet.WriteString(numberChars)
}
if useSymbols {
charSet.WriteString(symbolChars)
}
if charSet.Len() == 0 {
return "", fmt.Errorf("no character sets selected")
}
password := make([]byte, length)
for i := range password {
randomIndex, err := randomInt(charSet.Len())
if err != nil {
return "", fmt.Errorf("error generating random password: %v", err)
}
password[i] = charSet.String()[randomIndex]
}
return string(password), nil
}
func main() {
length := flag.Int("length", 12, "Length of the password (default: 12)")
useUpper := flag.Bool("upper", true, "Include uppercase letters (default: true)")
useNumbers := flag.Bool("numbers", true, "Include numbers (default: true)")
useSymbols := flag.Bool("symbols", true, "Include special characters (default: true)")
flag.Parse()
password, err := generatePassword(*length, *useUpper, *useNumbers, *useSymbols)
if err != nil {
log.Fatalf("Error generating password: %v", err)
}
fmt.Println("Generated password:", password)
}