Home > Article > Backend Development > How Can I Efficiently Generate All Possible N-Character Passwords in Go?
In password cracking exercises, it is crucial to generate all possible n-character passwords using a specified character set. Here's an efficient solution in Go:
Utilizing the n-ary Cartesian product, we can construct n-character passwords iteratively. For example, creating 2-character passwords from 'ABCDE':
Prod({A,B,C,D,E},{A,B,C,D,E}) = {(A,A),(A,B),(A,C),(A,D),(A,E),(B,A),(B,B),(B,C),(B,D),(B,E),...}
func NAryProduct(input string, n int) []string { if n <= 0 { return nil } prod := make([]string, len(input)) for i, char := range input { prod[i] = string(char) } for i := 1; i < n; i++ { next := make([]string, 0, len(input)*len(prod)) for _, word := range prod { for _, char := range input { next = append(next, word+string(char)) } } prod = next } return prod }
By recursively applying this method, you can generate password variations for any character set and password length. This iterative approach ensures memory usage remains low and all potential passwords are enumerated efficiently.
The above is the detailed content of How Can I Efficiently Generate All Possible N-Character Passwords in Go?. For more information, please follow other related articles on the PHP Chinese website!