In this tutorial, we will learn about how to validate password pattern in Golang using step by step guide. Securing user accounts is a fundamental aspect of software development, and a crucial part of this process is enforcing robust password patterns. As cyber threats continue to evolve, ensuring that user passwords meet certain criteria is essential to fortify the security of applications. Golang provides a versatile platform for building secure and efficient systems, and understanding how to validate password patterns in this language is a valuable skill for developers. We will explore how to implement effective password pattern validation using the Go programming language in the upcoming sections of this tutorial.
Why do we need to set the password for any user account?
In the computer world, the importance of password pattern validation cannot be overstated. It serves as a crucial component of cybersecurity, contributing to the overall protection of sensitive information and systems. I have mentioned some of the key reasons below which proof that password validation must be done before using any computer system or any software.
- Enhanced Security: Password pattern validation ensures that users create strong and secure passwords. This, in turn, strengthens the overall security posture, making it more challenging for unauthorized entities to gain access.
- Mitigation of Risks: Implementing a robust password pattern helps mitigate various cybersecurity risks, including unauthorized access, data breaches, and identity theft. By adhering to specific patterns, users create passwords that are less susceptible to hacking attempts.
- Adherence to Policies: Many organizations enforce password policies that include specific patterns or complexity requirements. Password pattern validation ensures users comply with these policies, fostering a secure computing environment.
- Prevention of Common Pitfalls: Validating password patterns helps prevent common pitfalls, such as the use of easily guessable passwords, common words, or patterns that are susceptible to dictionary attacks. This reduces the likelihood of successful attacks.
- Compliance Requirements: Various industry regulations and standards mandate the implementation of strong password policies. Password pattern validation aids organizations in meeting compliance requirements, avoiding potential legal and regulatory consequences.
- User Education: Through password pattern validation, users are educated about the importance of creating secure passwords. This awareness contributes to a culture of cybersecurity within organizations and among individual users.
How to Validate Password Pattern in Golang [Step by Step Guide]
Also Read: Understand Functions in Golang: [7 Best Examples]
There are several way to do this. Golang provides a package called password which can be used to validate one or more set of passwords against certain defined criteria. For the sake of this tutorial, I will not use the built-in Go module, instead, I have written a go module and defined the logic which takes the password as user input and validate it against the defined criteria. It will read each character typed in the password and validate it against certain condition. For example, we have set below conditions which must be satisfied to pass the validation check.
- Password length must be 8 or more character long
- Password must contain one or more lower case character
- Password must contain one or more upper case character
- Password must contain one or more digit
- Password must contain one or more special character
If any of the above condition is failed, the password validation check will fail and reports the error on standard output(on console). Let us implement the logic in below code and then will understand it’s execution flow.
package main import ( "fmt" "strings" "unicode" ) func validatePassword(password string) []string { const specialChar = "!@#$%^&*()-_=+,.:;?{}[]<>" var errors []string hasUpper := false hasLower := false hasDigit := false hasSpecialChar := false if len(password) < 8 { errors = append(errors, "Password length must be 8 or more character long") } for _, ch := range password { switch { case unicode.IsLower(ch): hasLower = true case unicode.IsUpper(ch): hasUpper = true case unicode.IsDigit(ch): hasDigit = true case strings.ContainsRune(specialChar, ch): hasSpecialChar = true } } if !hasLower { errors = append(errors, "Password must contain one or more lower case character") } if !hasUpper { errors = append(errors, "Password must contain one or more upper case character") } if !hasDigit { errors = append(errors, "Password must contain one or more digit") } if !hasSpecialChar { errors = append(errors, "Password must contain one or more special character") } return errors } func main() { password := "linuxnasa" output := validatePassword(password) if output == nil { fmt.Println("Valid Password") } else { fmt.Println("Invalid Password!!, Please follow below pattern") for _, mes := range output { fmt.Println(mes) } } }
Code Explanation
- I have imported few packages inside the import() block which are required to develop the password validation module.
- In the main() function, I have created a variable called “password” in which we are storing the value “linuxnasa” as password.
- I have created a new function called “validatePassword()” in which I have passed the given password value to be validated.
- Inside the validatePassword() function, I have created a constant called “specialChar”. This variable will store the special characters. Any given password must use one or more special character from this list.
- Next, I have created four variables namely, hasUpper, hasLower, hasDigit, hasSpecialChar and initialized their values to false. When checking any given password, we will change the variables value to true if one or more characters satisfy the requirement. For example in the given password value “linuxnasa”, it contains one or more lower character, so we will update the variable “hasLower” value as true and rest of the variables will remain false.
- Next, I have created a new slice called errors[]. It will store all the check errors in the given password. It will be returned as function return value.
- After the validatePassword() function value is returned to the main function, I have used for loop to iterate over the errros[] slice and return all the errors reported during the given password validation.
Let us now execute above code with the given password value as “linuxnasa”. Below is the returned output. As you notice the output, the password validation has failed and it has returned the set of errors indicating how the password format should be in order to pass the validation check.
OUTPUT
$ go run main.go Invalid Password!!, Please follow below pattern Password must contain one or more upper case character Password must contain one or more digit Password must contain one or more special character
Next, we will change the value of password in the code which does salify the validation criteria and execute again. Let us modify our code and assign below value to the variable “password”.
func main() { password := "Linux12@nasa" output := validatePassword(password) ........................................................ ........................................................ }
$ go run main.go Valid Password
Summary
We have successfully created a simple Golang code to validate any given password. You can add more to this code to make the password policy more hardening. For example, adding the password expiry, tracking the password history and so on. You can integrate this module with your application where you require a user to login before getting access to the application.