aboutsummaryrefslogtreecommitdiff
path: root/passgen.c
blob: 0139292a4f9a7b6c259befe23906a54fb8e5a62f (plain) (blame)
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
#include <unistd.h>

#define DEFAULT_GRAMMAR "Cvccvc!##"

// i, o excluded due to potentially confusing 1/l/i + 0/o
// y included as a vowel because it kinda is one
#define VOWELS "aeuy"
#define CONSONANTS "bcdfghkmnprstvwxz"
#define NUMBERS "1234567890"
#define SYMBOLS "@#$%^&*_-+=()[]{}"

int main(int argc, char *argv[])
{
  char *grammar = DEFAULT_GRAMMAR;
  int grammar_size = sizeof(DEFAULT_GRAMMAR)-1;

  if (argc == 2) {
    // Take first argument as the grammar
    grammar = argv[1];
    grammar_size = strlen(grammar);
  } else if (argc == 4) {
    // Take arguments as triplets, specials, numbers
    // atoi might be scuffed but so be it (it just goes = 0 if invalid input)
    int triplets = atoi(argv[1]);
    int specials = atoi(argv[2]);
    int numbers = atoi(argv[3]);

    if (triplets < 1) {
      printf("ERROR: Cannot have less than one triplet.");
      return 1;
    }

    grammar_size = triplets * 3 + specials + numbers;
    grammar = malloc(grammar_size + 1);
    grammar[grammar_size] = 0;

    memcpy(grammar, "Cvc", 3);
    for (int i = 1; i < triplets; ++i)
      memcpy(grammar + (i * 3), "cvc", 3);

    memset(grammar + (triplets * 3), '!', specials);
    memset(grammar + (triplets * 3) + specials, '#', numbers);
    //printf("Custom: %s\n", grammar);
  }

  char password[grammar_size];

  // seed RNG; this isn't very good, but it's enough (for now)
  srand(time(NULL) + getpid() % 420 - 69);
  
  for (int i = 0; i < grammar_size; ++i) {
    char c = grammar[i];

    bool caps = false;
    if (c >= 'A' && c <= 'Z') {
      caps = true;
      c += 'a' - 'A';
    }

    char *class;
    int class_size = 0;
#define setClass(cl) \
    class = cl; \
    class_size = sizeof(cl)-1; \
    break;

    switch (c) {
    case 'c':
      setClass(CONSONANTS);
    case 'v':
      setClass(VOWELS);
    case '!':
      setClass(SYMBOLS);
    case '#':
      setClass(NUMBERS);
    default:
      printf("ERROR: Invalid grammar character '%c'.\n", c);
      if (grammar != (char*)DEFAULT_GRAMMAR)
        free(grammar);
      return 1;
    }

    do {
      password[i] = class[rand() % class_size] - (caps ? 'a' - 'A' : 0);
    } while (i != 0 && password[i] == password[i-1]);
  }

  if (grammar != (char*)DEFAULT_GRAMMAR)
    free(grammar);

  printf("%s\n", password);

  return 0;
}