Question

Some years back when I was still a beginner at programming, I found some code online that could generate a bruteforce-code given an offset.

So for instance, if I did GetPassword(1) it would return "a", and if I did GetPassword(2) it would return "b" etc.

Every increment of the offset would provide the next possible combination of strings. A minimum and maximum length of the "password to guess" could also be provided.

Now I have no idea where this code is, or what the algorithm is called. I want to implement one myself, since I need it for URL-enshortening purposes. A user generates a URL that I want to look somewhat long these lines: http://fablelane.com/i/abc where "abc" is the code.

Was it helpful?

Solution

You can think of the output from GetPassword as a number in a different base. For example if GetPassword can output upper and lower case alphanumeric then it is in base 62 -> 26 letters + 26 letters + 10 digits.

GetPassword must convert from base 10 to base 62 in this case. You can use a look up array to find the output characters.

You can convert from one base to another by using an algorithm such as this:

Another stackoverflow post

OTHER TIPS

This is base 26 encoding end decoding:

public static string Encode(int number){
    number = Math.Abs(number);
    StringBuilder converted = new StringBuilder();
    // Repeatedly divide the number by 26 and convert the
    // remainder into the appropriate letter.
    do
    {
        int remainder = number % 26;
        converted.Insert(0, (char)(remainder + 'a'));
        number = (number - remainder) / 26;
    } while (number > 0);

    return converted.ToString();
}

public static int Decode(string number) {
    if (number == null) throw new ArgumentNullException("number");
    int s = 0;
    for (int i = 0; i < number.Length; i++) {
        s += (number[i] - 'a');
        s = i == number.Length - 1 ? s : s * 26;
    }
    return s;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top