/
password_utility.go
250 lines (217 loc) · 6.41 KB
/
password_utility.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
// Copyright 2014 Brian J. Downs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Simple library for working with passwords in Go.
// All generated passwords are going to be a minimum of 8
// characters in length.
package GoPasswordUtilities
import (
"bufio"
"bytes"
"crypto/md5"
"crypto/rand"
"crypto/sha256"
"crypto/sha512"
"fmt"
"log"
"os"
"regexp"
"strings"
)
const (
characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+,.?/:;{}[]~"
wordsLocation = "/usr/share/dict/words"
)
var (
passwordScores = map[int]string{
0: "Horrible",
1: "Weak",
2: "Medium",
3: "Strong",
4: "Very Strong"}
)
type Password struct {
Pass string
Length int
Score int
ContainsUpper bool
ContainsLower bool
ContainsNumber bool
ContainsSpecial bool
DictionaryBased bool
}
type SaltConf struct {
Length int
}
// New is used when a user enters a password as well as the
// being called from the GeneratePassword function.
func New(password string) *Password {
return &Password{Pass: password, Length: len(password)}
}
// GeneratePassword will generate and return a password as a string and as a
// byte slice of the given length.
func GeneratePassword(length int) *Password {
passwordBuffer := new(bytes.Buffer)
randBytes := make([]byte, length)
if _, err := rand.Read(randBytes); err == nil {
for j := 0; j < length; j++ {
tmpIndex := int(randBytes[j]) % len(characters)
char := characters[tmpIndex]
passwordBuffer.WriteString(string(char))
}
}
return New(passwordBuffer.String())
}
// GenerateVeryStrongPassword will generate a "Very Strong" password.
func GenerateVeryStrongPassword(length int) *Password {
for {
p := GeneratePassword(length)
p.ProcessPassword()
if p.Score == 4 {
return p
}
}
}
// getRandomBytes will generate random bytes. This is for internal
// use in the library itself.
func getRandomBytes(length int) []byte {
randomData := make([]byte, length)
if _, err := rand.Read(randomData); err != nil {
log.Fatalf("%v\n", err)
}
return randomData
}
// MD5 sum for the given password. If a SaltConf
// pointer is given as a parameter a salt with the given
// length will be returned with it included in the hash.
func (p *Password) MD5(saltConf ...*SaltConf) ([16]byte, []byte) {
if len(saltConf) > 0 {
var saltLength int
for _, i := range saltConf[0:] {
saltLength = i.Length
}
salt := getRandomBytes(saltLength)
return md5.Sum([]byte(fmt.Sprintf("%s%x", p.Pass, salt))), salt
}
return md5.Sum([]byte(p.Pass)), nil
}
// SHA256 sum for the given password. If a SaltConf
// pointer is given as a parameter a salt with the given
// length will be returned with it included in the hash.
func (p *Password) SHA256(saltConf ...*SaltConf) ([32]byte, []byte) {
if len(saltConf) > 0 {
var saltLength int
for _, i := range saltConf[0:] {
saltLength = i.Length
}
salt := getRandomBytes(saltLength)
return sha256.Sum256([]byte(fmt.Sprintf("%s%x", p.Pass, salt))), salt
}
return sha256.Sum256([]byte(p.Pass)), nil
}
// SHA512 sum for the given password. If a SaltConf
// pointer is given as a parameter a salt with the given
// length will be returned with it included in the hash.
func (p *Password) SHA512(saltConf ...*SaltConf) ([64]byte, []byte) {
if len(saltConf) > 0 {
var saltLength int
for _, i := range saltConf[0:] {
saltLength = i.Length
}
salt := getRandomBytes(saltLength)
return sha512.Sum512([]byte(fmt.Sprintf("%s%x", p.Pass, salt))), salt
}
return sha512.Sum512([]byte(p.Pass)), nil
}
// GetLength will provide the length of the password. This method is
// being put on the password struct in case someone decides not to
// do a complexity check.
func (p *Password) GetLength() int {
return p.Length
}
// ProcessPassword will parse the password and populate the Password struct attributes.
func (p *Password) ProcessPassword() {
matchLower := regexp.MustCompile(`[a-z]`)
matchUpper := regexp.MustCompile(`[A-Z]`)
matchNumber := regexp.MustCompile(`[0-9]`)
matchSpecial := regexp.MustCompile(`[\!\@\#\$\%\^\&\*\(\\\)\-_\=\+\,\.\?\/\:\;\{\}\[\]~]`)
if p.Length < 8 {
log.Fatalln("password isn't long enough for evaluation")
}
if matchLower.MatchString(p.Pass) {
p.ContainsLower = true
p.Score++
}
if matchUpper.MatchString(p.Pass) {
p.ContainsUpper = true
p.Score++
}
if matchNumber.MatchString(p.Pass) {
p.ContainsNumber = true
p.Score++
}
if matchSpecial.MatchString(p.Pass) {
p.ContainsSpecial = true
p.Score++
}
if searchDict(p.Pass) {
p.DictionaryBased = true
p.Score--
}
}
// searchDict will search the words list for an occurance of the
// given word. Requires wamerican || wbritish || wordlist || words
// to be installed.
func searchDict(word string) bool {
file, err := os.Open(wordsLocation)
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
if strings.Contains(strings.ToLower(scanner.Text()), word) {
return true
}
}
return false
}
// GetScore will provide the score of the password.
func (p *Password) GetScore() int {
return p.Score
}
// HasUpper indicates whether the password contains an upper case letter.
func (p *Password) HasUpper() bool {
return p.ContainsUpper
}
// HasLower indicates whether the password contains a lower case letter.
func (p *Password) HasLower() bool {
return p.ContainsLower
}
// HasNumber indicates whether the password contains a number.
func (p *Password) HasNumber() bool {
return p.ContainsNumber
}
// HasSpecial indicates whether the password contains a special character.
func (p *Password) HasSpecial() bool {
return p.ContainsSpecial
}
// ComplexityRating provides the rating for the password.
func (p *Password) ComplexityRating() string {
return passwordScores[p.Score]
}
// InDictionary will return true or false if it's been detected
// that the given password is a dictionary based.
func (p *Password) InDictionary() bool {
return p.DictionaryBased
}