uni

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

sign.c (1214B)


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