Home  >  Article  >  Backend Development  >  How Can I Efficiently Generate All Possible N-Character Passwords in Go?

How Can I Efficiently Generate All Possible N-Character Passwords in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-11-23 06:57:11347browse

How Can I Efficiently Generate All Possible N-Character Passwords in Go?

Iterative n-Character Password Generation 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn