Introduction
This program validates a given password against specific criteria to ensure its strength and security. Strong passwords are crucial for protecting user accounts and sensitive information. By implementing this program, you’ll gain hands-on experience with string manipulation and regular expressions in Go.
Objective
The objective of this project is to build a password validation tool that enforces strong password policies, including minimum length, presence of uppercase letters, numbers, and special characters. This enhances your understanding of Go programming concepts and strengthens your skills in writing secure code.
Code
package main
import (
"fmt"
"regexp"
)
func validatePassword(password string) (bool, string) {
// Criteria for a strong password
const minLength = 8
if len(password) < minLength {
return false, fmt.Sprintf("Password must be at least %d characters long.", minLength)
}
// Check for at least one uppercase letter
hasUpperCase := regexp.MustCompile(`[A-Z]`).MatchString(password)
if !hasUpperCase {
return false, "Password must contain at least one uppercase letter."
}
// Check for at least one digit
hasDigit := regexp.MustCompile(`\d`).MatchString(password)
if !hasDigit {
return false, "Password must contain at least one digit."
}
// Check for at least one special character
hasSpecialChar := regexp.MustCompile(`[!@#$%^&*(),.?":{}|<>]`).MatchString(password)
if !hasSpecialChar {
return false, "Password must contain at least one special character."
}
return true, "Password is valid."
}
func main() {
var password string
fmt.Println("Welcome to the Password Validator!")
fmt.Println("Please enter a password to validate:")
fmt.Scanln(&password)
valid, message := validatePassword(password)
if valid {
fmt.Println("Success:", message)
} else {
fmt.Println("Error:", message)
}
}
Explanation
The program structure is as follows:
- Validation Function: The
validatePassword
function checks the password against the following criteria:- Minimum length (8 characters).
- At least one uppercase letter using regular expressions.
- At least one digit using regular expressions.
- At least one special character using regular expressions.
- Main Function: The main function takes user input for the password, passes it to the validation function, and prints appropriate feedback.
How to Run the Program
- Ensure you have Go installed on your system. You can download it from
Go’s official website. - Save the code in a file named
password_validator.go
. - Open a terminal and navigate to the directory containing the file.
- Run the program with the following command:
go run password_validator.go
- Enter a password when prompted and receive feedback on its validity.
Copyright © Learn Programming. All rights reserved.