Created
January 15, 2014 12:49
-
-
Save tuxillo/8435621 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <err.h> | |
#define KEYFILE "otpkey.dat" | |
#define MAXMSGLEN 1024 | |
char ktext[MAXMSGLEN] = {0}; | |
void | |
genkey(const char *path) | |
{ | |
FILE *f, *r; | |
size_t rbytes, wbytes; | |
printf("Generating key ... \n"); | |
if ((r = fopen("/dev/random", "r")) == NULL) | |
err(1, "Failed to open random(4)"); | |
if ((f = fopen(KEYFILE, "w+")) == NULL) | |
err(1, "Failed to create key file"); | |
rbytes = fread(ktext, MAXMSGLEN, 1, r); | |
wbytes = fwrite(ktext, MAXMSGLEN, 1, f); | |
if (rbytes != wbytes) | |
errx(1, "Failed to write key file"); | |
fclose(r); | |
fclose(f); | |
} | |
void | |
loadkey(const char *path) | |
{ | |
FILE *f; | |
size_t rbytes; | |
printf("Loading key ... \n"); | |
f = fopen(KEYFILE, "rw"); | |
if (f == NULL) | |
errx(1, "Failed to load key file"); | |
rbytes = fread(ktext, MAXMSGLEN, 1, f); | |
if (rbytes != 1) | |
errx(1, "Failed to read key file. %jd bytes read", rbytes); | |
fclose(f); | |
} | |
int | |
encrypt(const char *msg, char *ctext, size_t len) | |
{ | |
int i; | |
for (i = 0; i < len; i++) { | |
ctext[i] = msg[i] ^ ktext[i]; | |
} | |
} | |
int | |
decrypt(const char *ctext, char *msg, size_t len) | |
{ | |
int i; | |
for (i = 0; i < len; i++) { | |
msg[i] = ctext[i] ^ ktext[i]; | |
} | |
} | |
void | |
usage(const char *progname) | |
{ | |
fprintf(stdout, "usage: %s [-ed]\n", progname); | |
} | |
int | |
main(int argc, char *argv[]) | |
{ | |
FILE *kf; | |
char c; | |
char buf[MAXMSGLEN]; | |
char cbuf[MAXMSGLEN]; | |
int opt_encryt = 0; | |
int opt_decrypt = 0; | |
bzero(buf, MAXMSGLEN); | |
bzero(cbuf, MAXMSGLEN); | |
while ((c = getopt(argc, argv, "ed")) != -1) { | |
switch(c) { | |
case 'e': | |
opt_encryt = 1; | |
break; | |
case 'd': | |
opt_decrypt = 1; | |
break; | |
default: | |
usage(argv[0]); | |
} | |
} | |
if ((kf = fopen(KEYFILE, "r")) == NULL) | |
genkey(KEYFILE); | |
else | |
loadkey(KEYFILE); | |
if (opt_encryt && opt_decrypt) | |
errx(1, "You can't encrypt and decrypt at once"); | |
if (opt_encryt) { | |
fgets(buf, MAXMSGLEN, stdin); | |
encrypt(buf, cbuf, strlen(buf)); | |
fprintf(stdout, "Encrypted: %s\n", cbuf); | |
} else if (opt_decrypt) { | |
decrypt(cbuf, buf, strlen(cbuf)); | |
fprintf(stdout, "Decrypted: %s\n", buf); | |
} else { | |
usage(argv[0]); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment