Created
June 9, 2022 09:19
-
-
Save orip/5066e3dc8da203ec38818f481a256c97 to your computer and use it in GitHub Desktop.
Generate secure passwords in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/rand" | |
"flag" | |
"fmt" | |
"math/big" | |
) | |
func GenerateSecurePassword(n int, alphabet string) (string, error) { | |
alphabetLength := big.NewInt(int64(len(alphabet))) | |
ret := make([]byte, n) | |
for i := 0; i < n; i++ { | |
charIndex, err := rand.Int(rand.Reader, alphabetLength) | |
if err != nil { | |
return "", err | |
} | |
ret[i] = alphabet[charIndex.Int64()] | |
} | |
return string(ret), nil | |
} | |
func GenerateAlphaNumericPassword(n int) (string, error) { | |
const alphaNumericAlphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" | |
return GenerateSecurePassword(n, alphaNumericAlphabet) | |
} | |
func main() { | |
n := flag.Int("n", 12, "password length") | |
flag.Parse() | |
password, err := GenerateAlphaNumericPassword(*n) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("Password:", password) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment