commit 810965a9fb56f79cca20fa0632bb7b7cdf81cf9b Author: Daniel Cortés Date: Sun Oct 13 18:40:32 2019 -0300 initial commit <3 diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..4917c92 --- /dev/null +++ b/Makefile @@ -0,0 +1,5 @@ +all: main.c strtoui.h + gcc -Wall main.c strtoui.h -o chars -lsodium + +clean: + rm chars main.o diff --git a/chars b/chars new file mode 100755 index 0000000..25e003a Binary files /dev/null and b/chars differ diff --git a/main.c b/main.c new file mode 100644 index 0000000..ee8c743 --- /dev/null +++ b/main.c @@ -0,0 +1,44 @@ +#include "stdio.h" +#include "stdlib.h" +#include "limits.h" +#include "sodium.h" +#include "strtoui.h" + +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; + return j; +} + +int main(int argc, char *argv[]) { + if(argc == 1) { + puts("Usage: chars [length]"); + puts(" Max length is 1024"); + exit(EXIT_SUCCESS); + } + + unsigned int len; + enum strtoui_error error = strtoui(&len, argv[1], 10); + if(error != STRTOUI_SUCCESS){ + fputs("Bad input\n", stderr); + exit(EXIT_FAILURE); + }else if (len > 1024) { + fputs("The length is to big\n", stderr); + exit(EXIT_FAILURE); + } + + char lower_range = 0x20; + char upper_range= 0x7e; + + char data[len]; + randombytes_buf(data, sizeof len); + + 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]); + } + printf("\n"); + + exit(EXIT_SUCCESS); +} diff --git a/strtoui.h b/strtoui.h new file mode 100644 index 0000000..606cc4c --- /dev/null +++ b/strtoui.h @@ -0,0 +1,31 @@ +#ifndef STRTOUI_H +#define STRTOUI_H + +#include "stdlib.h" +#include "ctype.h" +#include "limits.h" +#include "errno.h" + +enum strtoui_error{ + STRTOUI_SUCCESS, + STRTOUI_OVERFLOW, + STRTOUI_UNDERFLOW, + STRTOUI_INCONVERTIBLE +}; + +enum strtoui_error strtoui(unsigned int *out, char *s, int base) { + char *end; + 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)) + return STRTOUI_OVERFLOW; + if(l < 0|| (errno == ERANGE && l == LONG_MIN)) + return STRTOUI_UNDERFLOW; + if(*end != '\0') + return STRTOUI_INCONVERTIBLE; + *out = l; + return STRTOUI_SUCCESS; +} + +#endif