Files
create-task-apcomp/password/password.go
2026-02-23 08:26:47 -05:00

71 lines
2.0 KiB
Go

package password
import (
"fmt"
"regexp"
"strings"
)
// Check checks if password is valid, and returns message, and if its a strong password
func Check(input string, wordList, passwordList []string) (string, error) {
// Variables to check state of password
hasCapitalLetter := false
hasSpecialCharacter := false
isTwelveCharacters := false
hasNumber := false
// Check if password is shorter than 8 characters
if len(input) < 2 {
return "Weak password", fmt.Errorf("password cannot be shorter than 12 characters")
} else {
isTwelveCharacters = true
}
// Check if password contains a number and a special character and a capital letter
for _, letter := range input {
// Check ASCII code to see if has special character
if letter >= 33 && letter <= 47 || letter >= 58 && letter <= 62 {
hasSpecialCharacter = true
}
// Check ASCII code to see if password contains a number
if letter >= 48 && letter <= 57 {
hasNumber = true
}
// Check ASCII code to see if password contains a capital letter
if letter >= 65 && letter <= 90 {
hasCapitalLetter = true
}
// Check ASCII code to see if there is a space
if letter == 32 {
return "Weak password", fmt.Errorf("password cannot contain a space")
}
}
// Check if password is in common passwords
for _, entry := range passwordList {
if strings.Contains(entry, input) {
return "Weak password", fmt.Errorf("password found inside common passwords")
}
}
// Check if password contains any common words
re, _ := regexp.Compile(`[^a-zA-Z]+`) // Use regex to match anything thats not a letter
// Replace all nonletter characters with blank space
strippedPassword := re.ReplaceAllString(input, "")
// Iterate through common words and see if input contains any
for _, word := range wordList {
if strings.Contains(word, strippedPassword) {
return "Weak password", fmt.Errorf("password contains common word from wordlist")
}
}
if !(hasNumber && hasSpecialCharacter && isTwelveCharacters && hasCapitalLetter) {
return "Weak password", nil
}
return "Strong password", nil
}