From 4875a6cf6a7f01c775df6ff70f7dd1116429d8f4 Mon Sep 17 00:00:00 2001 From: Kyle K Date: Fri, 18 Feb 2011 21:02:38 -0600 Subject: crypt works --- crypt.cpp | 77 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 72 insertions(+), 5 deletions(-) (limited to 'crypt.cpp') diff --git a/crypt.cpp b/crypt.cpp index e72bd97..5f0d01d 100644 --- a/crypt.cpp +++ b/crypt.cpp @@ -5,7 +5,10 @@ */ #include "crypt.h" + +#ifndef DEBUG #define DEBUG +#endif /* forward declaration of variables from crypt_args.h */ extern char *fname; @@ -23,8 +26,8 @@ struct rsakey_t parse_key(FILE *file) struct rsakey_t key = { 0, 0, 0}; /* used for line reading */ - size_t line_sz = 80; - char *line = (char *) malloc(sizeof(char) * line_sz); + size_t line_sz = 0; + char *line = NULL; while (getline(&line, &line_sz, file) != -1) { @@ -33,7 +36,9 @@ struct rsakey_t parse_key(FILE *file) sscanf(line, "\t%lu\n", &key.n); } - free(line); + if (line) + free(line); + return key; } @@ -53,8 +58,15 @@ int main(int argc, char **argv) FILE *fname_fl = fopen(fname, "r"); FILE *keyfname_fl = fopen(keyfname, "r"); FILE *outfname_fl = fopen(outfname, "w"); - if (fname_fl == NULL || keyfname_fl == NULL || outfname_fl == NULL) - { + if (fname_fl == NULL) { + fprintf(stderr, "fopen: \"%s\", %s\n", fname, strerror(errno)); + exit(EXIT_FAILURE); + } + if (keyfname_fl == NULL) { + fprintf(stderr, "fopen: \"%s\", %s\n", keyfname, strerror(errno)); + exit(EXIT_FAILURE); + } + if (outfname_fl == NULL) { perror("fopen"); exit(EXIT_FAILURE); } @@ -80,6 +92,61 @@ int main(int argc, char **argv) exit(EXIT_FAILURE); } + if (mode == 0) /* encrypt */ + { + char *line = NULL; + size_t len = 0; + ssize_t read; + + unsigned int readin = 0; + BigUnsigned calc = 0; + string writeout; + const char *outstr = NULL; + while ((read = getline(&line, &len, fname_fl)) != -1) + { + sscanf(line, "%u\n", &readin); + printf("read in: \"%u\"", readin); + calc = modexp(BigUnsigned(readin), key.e, key.n); + writeout = bigIntegerToString(calc); + cout << ", encrypted: " << writeout << endl; + outstr = writeout.c_str(); + fprintf(outfname_fl, "%s\n", outstr); + } + + free(line); + } + else /* decrypt */ + { + char *line = NULL; + size_t len = 0; + ssize_t read; + + char readin[100]; + BigUnsigned calc = 0; + BigInteger tmpbig = 0; + string writeout; + string tmpstr; + const char *outstr = NULL; + while ((read = getline(&line, &len, fname_fl)) != -1) + { + sscanf(line, "%s\n", readin); + printf("read in: \"%s\"", readin); + string tmpstr(readin); + tmpbig = stringToBigInteger(tmpstr); + calc = modexp(tmpbig, key.d, key.n); + writeout = bigIntegerToString(calc); + cout << ", decrypted: " << writeout << endl; + outstr = writeout.c_str(); + fprintf(outfname_fl, "%s\n", outstr); + } + + free(line); + } + + fclose(fname_fl); + fclose(keyfname_fl); + fclose(outfname_fl); + return 0; } -- cgit v1.2.3