Password generator in D

So I recently decided to go back and try and master the D language, after an extremely long pause.

So here's a simple and crude program, that can generate passwords. I'm sure many of you have already written a C++ equivalent for yourselves so it should be familiar.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import std.array;
import std.conv;
import std.random;
import std.stdio;

void main(string[] args)
{
    immutable string[] modes = [
        // Mode 0
        "abcdefghijklmnopqrstuvwxyz",

        // Mode 1
        "abcdefghijklmnopqrstuvwxyz"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ",

        // Mode 2
        "abcdefghijklmnopqrstuvwxyz"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "0123456789",

        // Mode 3
        "abcdefghijklmnopqrstuvwxyz"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "0123456789"
        "~`!@#$%^&*()_-+=|\\{[}]:;\"'<,>.?/"
    ];

    void printUsage(string errorMessage = "")
    {
        writeln("\nPassGen usage:");
        writeln("\n\t", args[0], " n m\n\nWhere `n' and `m' are unsigned integers:");
        writeln("\tn in [0, ", modes.length, ") representing the Mode, and");
        writeln("\tm >= 0, representing the number of characters.");

        if (!errorMessage.empty)
            writeln(errorMessage);

        writeln();
    }

    if (args.length != 3)
    {
        printUsage();
        return;
    }

    const size_t n = parse!size_t(args[1]);

    if (n >= modes.length)
    {
        printUsage("Bad `n' parsed as \"" ~ to!string(n) ~ "\".");
        return;
    }

    char[] password;

    password.length = parse!size_t(args[2]);

    foreach (ref char c; password)
            c = modes[n][uniform(0, modes[n].length)];

    writeln(password);
}

Last edited on
closed account (Dy7SLyTq)
huh this seems a lot like c++. im guessing that immutable is const, line 8 would be a string*. is the function like in php then, when it just skips the function until called? does ~ cat strings on line 51? whats to!string(n)?
why do you have a function within another function, also D actually looks quite amazing. The day they allow it in computer olympiads is the day I will start using it though.

It is "crude" as you say, but why are you posting it? For review? help?
Although come to think of it, it is not that crude: It has a pretty good defensive design and it generates a completely random password. You could try and make it ensure that there are a certain amount of each type of character.
closed account (o1vk4iN6)
parse!size_t(args[2]);

That syntax is really ... that's suppose to be a template arguement right.

1
2
3
parse!size_t(args[2]);
parse!(size_t)(args[2]);
parse<size_t>(args[2]);


It solves the >> problem but i think it looks worse and is harder to understand.
Last edited on
Topic archived. No new replies allowed.