Generating a Secure 8-Character Password Using Go Language
23 views
Creating a strong 8-character password in Go involves ensuring it meets certain criteria such as including upper and lowercase letters, numbers, and special characters. Here's how you can generate such a password in Go:
package main
import (
"crypto/rand"
"fmt"
"math/big"
)
const (
lowerChars = "abcdefghijklmnopqrstuvwxyz"
upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numberChars = "0123456789"
specialChars = "!@#$%^&*()-_=+[]{}|;:,.<>?/`~"
)
var allChars = lowerChars + upperChars + numberChars + specialChars
func generateStrongPassword(length int) (string, error) {
if length < 8 {
return "", fmt.Errorf("password length must be at least 8 characters")
}
password := make([]byte, length)
// Ensure password contains at least one character from each category
categories := []string{lowerChars, upperChars, numberChars, specialChars}
for i, category := range categories {
char, err := randomCharFrom(category)
if err != nil {
return "", err
}
password[i] = char
}
// Fill the rest of the password with random characters from all categories
for i := len(categories); i < length; i++ {
char, err := randomCharFrom(allChars)
if err != nil {
return "", err
}
password[i] = char
}
// Shuffle password
shuffle(password)
return string(password), nil
}
func randomCharFrom(chars string) (byte, error) {
n, err := rand.Int(rand.Reader, big.NewInt(int64(len(chars))))
if err != nil {
return 0, err
}
return chars[n.Int64()], nil
}
func shuffle(bytes []byte) {
for i := range bytes {
j, _ := rand.Int(rand.Reader, big.NewInt(int64(len(bytes))))
bytes[i], bytes[j.Int64()] = bytes[j.Int64()], bytes[i]
}
}
func main() {
password, err := generateStrongPassword(8)
if err != nil {
fmt.Println("Error generating password:", err)
return
}
fmt.Println("Generated strong password:", password)
}
Explanation
-
Constants: Define the characters for each category (lowercase, uppercase, numbers, special characters).
-
Generate Password:
- Verify that the requested password length is at least 8 characters.
- Ensure the password contains at least one character from each category by iterating over the categories and selecting a random character from each.
- Fill the rest of the password with random characters from the combined pool of all characters.
- Finally, shuffle the characters to ensure the initial characters (from each category) are not in predictable positions.
-
Helper Functions:
randomCharFrom(chars string): Selects a random character from the provided string of characters.shuffle(bytes []byte): Shuffles the characters in the byte slice to add randomness to their positions.
Make sure to run and test the code to verify that it works as expected. This example ensures that the generated password is strong and meets the criteria.