diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7cc6b13 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +chars diff --git a/Makefile b/Makefile index 4917c92..9da6560 100644 --- a/Makefile +++ b/Makefile @@ -2,4 +2,4 @@ all: main.c strtoui.h gcc -Wall main.c strtoui.h -o chars -lsodium clean: - rm chars main.o + rm chars diff --git a/chars b/chars deleted file mode 100755 index 25e003a..0000000 Binary files a/chars and /dev/null differ diff --git a/main.c b/main.c index ee8c743..4c5056b 100644 --- a/main.c +++ b/main.c @@ -4,6 +4,9 @@ #include "sodium.h" #include "strtoui.h" +/** + * Maps a number that is between i_min and i_max to the range o_min and o_max + */ int map(int i, int i_min, int i_max, int o_min, int o_max) { double r = (double)(o_max - o_min) / (double)(i_max - i_min); int j = (double) (i - i_min) * r + o_min; @@ -11,32 +14,35 @@ int map(int i, int i_min, int i_max, int o_min, int o_max) { } int main(int argc, char *argv[]) { + //if doesnt have any argument just show a usage info if(argc == 1) { - puts("Usage: chars [length]"); - puts(" Max length is 1024"); + puts("Usage:\tchars [length]"); + puts("\t0 > lenght > UINT_MAX"); + puts("Description:"); + puts("\t Generates a random string with the specified length"); exit(EXIT_SUCCESS); } + //read the length argument and parse it to a an unsigned int unsigned int len; enum strtoui_error error = strtoui(&len, argv[1], 10); - if(error != STRTOUI_SUCCESS){ - fputs("Bad input\n", stderr); + if(error == STRTOUI_OVERFLOW){ + fputs("The input is too big\n", stderr); exit(EXIT_FAILURE); - }else if (len > 1024) { - fputs("The length is to big\n", stderr); + }else if(error == STRTOUI_UNDERFLOW) { + fputs("The input must be bigger than 0\n", stderr); + exit(EXIT_FAILURE); + }else if(error == STRTOUI_INCONVERTIBLE) { + fputs("The input isn't valid\n", stderr); exit(EXIT_FAILURE); } - char lower_range = 0x20; - char upper_range= 0x7e; - - char data[len]; - randombytes_buf(data, sizeof len); - + //prints random numbers in the bounds specified as chars + char lower_bound = 0x20; + char upper_bound= 0x7e; for(int i = 0; i < len; i++) { - int random = randombytes_uniform(upper_range); - data[i] = map(random, 0, upper_range, lower_range, upper_range); - printf("%c", data[i]); + int random = randombytes_uniform(upper_bound); + printf("%c", map(random, 0, upper_bound, lower_bound, upper_bound)); } printf("\n"); diff --git a/strtoui.h b/strtoui.h index 606cc4c..2d9bbcb 100644 --- a/strtoui.h +++ b/strtoui.h @@ -18,7 +18,7 @@ enum strtoui_error strtoui(unsigned int *out, char *s, int base) { if(s[0] == '\0' || isspace(s[0])) return STRTOUI_INCONVERTIBLE; long l = strtol(s, &end, base); - if(l > INT_MAX || (errno == ERANGE && l == LONG_MAX)) + if(l > UINT_MAX || (errno == ERANGE && l == LONG_MAX)) return STRTOUI_OVERFLOW; if(l < 0|| (errno == ERANGE && l == LONG_MIN)) return STRTOUI_UNDERFLOW;