forked from yunionio/cloudpods
/
seclib.go
90 lines (79 loc) · 2.04 KB
/
seclib.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
78
79
80
81
82
83
84
85
86
87
88
89
90
package seclib2
import (
"bytes"
"fmt"
"math/rand"
"strings"
)
const (
DIGITS = "23456789"
LETTERS = "abcdefghjkmnpqrstuvwxyz"
UPPERS = "ABCDEFGHJKMNPRSTUVWXYZ"
PUNC = "()~@#$%^&*-+={}[]:;<>,.?/"
ALL_DIGITS = "0123456789"
ALL_LETTERS = "abcdefghijklmnopqrstuvwxyz"
ALL_UPPERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ALL_PUNC = "~`!@#$%^&*()-_=+[]{}|:';\",./<>?"
)
type PasswordStrength struct {
Digits int
Lowercases int
Uppercases int
Punctuats int
}
var CHARS = fmt.Sprintf("%s%s%s%s", DIGITS, LETTERS, UPPERS, PUNC)
func RandomPassword2(width int) string {
if width < 6 {
width = 6
}
for {
ps := PasswordStrength{}
var buf bytes.Buffer
for i := 0; i < width; i += 1 {
index := rand.Intn(len(CHARS))
ch := CHARS[index]
if strings.IndexByte(DIGITS, ch) >= 0 {
ps.Digits += 1
} else if strings.IndexByte(LETTERS, ch) >= 0 {
ps.Lowercases += 1
} else if strings.IndexByte(UPPERS, ch) >= 0 {
ps.Uppercases += 1
} else if strings.IndexByte(PUNC, ch) >= 0 {
ps.Punctuats += 1
}
buf.WriteByte(ch)
}
if ps.Digits > 1 && ps.Lowercases > 1 && ps.Uppercases > 1 && ps.Punctuats >= 1 && ps.Punctuats <= 2 {
return buf.String()
}
}
}
func AnalyzePasswordStrenth(passwd string) PasswordStrength {
ps := PasswordStrength{}
for i := 0; i < len(passwd); i += 1 {
if strings.IndexByte(ALL_DIGITS, passwd[i]) >= 0 {
ps.Digits += 1
} else if strings.IndexByte(ALL_LETTERS, passwd[i]) >= 0 {
ps.Lowercases += 1
} else if strings.IndexByte(ALL_UPPERS, passwd[i]) >= 0 {
ps.Uppercases += 1
} else if strings.IndexByte(ALL_PUNC, passwd[i]) >= 0 {
ps.Punctuats += 1
}
}
return ps
}
func (ps PasswordStrength) Len() int {
return ps.Punctuats + ps.Uppercases + ps.Lowercases + ps.Digits
}
func (ps PasswordStrength) MeetComplexity() bool {
if ps.Punctuats > 0 && ps.Digits > 0 && ps.Lowercases > 0 && ps.Uppercases > 0 && ps.Len() >= 12 {
return true
} else {
return false
}
}
func MeetComplxity(passwd string) bool {
ps := AnalyzePasswordStrenth(passwd)
return ps.MeetComplexity()
}