uni

University stuff
git clone git://git.margiolis.net/uni.git
Log | Files | Refs | README | LICENSE

decrypt.c (1038B)


      1 #include <err.h>
      2 #include <stdio.h>
      3 #include <string.h>
      4 
      5 #include <openssl/bn.h>
      6 
      7 static const char *
      8 read_line(FILE *fp)
      9 {
     10 	char buf[2048];
     11 
     12 	if (fgets(buf, sizeof(buf), fp) == NULL)
     13 		err(1, "fgets");
     14 	return (strdup(buf));
     15 }
     16 
     17 static void
     18 printbn(char *str, BIGNUM *bn)
     19 {
     20 	char *s;
     21 
     22 	s = BN_bn2hex(bn);
     23 	printf("%s%s\n", str, s);
     24 	OPENSSL_free(s);
     25 }
     26 
     27 int
     28 main(int argc, char *argv[])
     29 {
     30 	BN_CTX *ctx;
     31 	BIGNUM *e, *n, *d, *c, *decrstr;
     32 	FILE *fp;
     33 
     34 	if (argc < 2) {
     35 		fprintf(stderr, "usage: %s input\n", *argv);
     36 		return (-1);
     37 	}
     38 	if ((fp = fopen(argv[1], "r")) == NULL)
     39 		err(1, "fopen(%s)", argv[1]);
     40 
     41 	ctx = BN_CTX_new();
     42 	e = BN_new();
     43 	n = BN_new();
     44 	d = BN_new();
     45 	c = BN_new();
     46 	decrstr = BN_new();
     47 
     48 	BN_hex2bn(&e, read_line(fp));
     49 	BN_hex2bn(&n, read_line(fp));
     50 	BN_hex2bn(&d, read_line(fp));
     51 	BN_hex2bn(&c, read_line(fp));
     52 
     53 	BN_mod_exp(decrstr, c, d, n, ctx);
     54 	printbn("", decrstr);
     55 	
     56 	fclose(fp);
     57 	OPENSSL_free(e);
     58 	OPENSSL_free(n);
     59 	OPENSSL_free(d);
     60 	OPENSSL_free(c);
     61 	OPENSSL_free(decrstr);
     62 	OPENSSL_free(ctx);
     63 
     64 	return (0);
     65 }