encrypt.c (1478B)
1 #include <err.h> 2 #include <stdio.h> 3 #include <unistd.h> 4 #include <string.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 *str, *encrstr, *decrstr; 33 BIGNUM *e, *n, *d; 34 FILE *fp; 35 int len = 0; 36 char buf[2048]; 37 38 if (argc < 2) { 39 fprintf(stderr, "usage: %s input\n", *argv); 40 return (-1); 41 } 42 if ((fp = fopen(argv[1], "r")) == NULL) 43 err(1, "fopen(%s)", argv[1]); 44 45 /* Read string from stdin */ 46 while (read(STDIN_FILENO, &buf[len++], 1) > 0) 47 ; 48 buf[--len] = '\0'; 49 50 ctx = BN_CTX_new(); 51 str = BN_new(); 52 encrstr = BN_new(); 53 decrstr = BN_new(); 54 e = BN_new(); 55 n = BN_new(); 56 d = BN_new(); 57 58 BN_hex2bn(&str, buf); 59 /* 60 * Assumes input from file produced by `priv -v`, so that we 61 * avoid duplicating code to recalculate p, q, e, n, d. 62 */ 63 BN_hex2bn(&e, read_line(fp)); 64 BN_hex2bn(&n, read_line(fp)); 65 BN_hex2bn(&d, read_line(fp)); 66 67 /* Encrypt message */ 68 BN_mod_exp(encrstr, str, e, n, ctx); 69 /* Decrypt message */ 70 BN_mod_exp(decrstr, encrstr, d, n, ctx); 71 72 printbn("received: ", str); 73 printbn("encrypted: ", encrstr); 74 printbn("decrypted: ", decrstr); 75 76 fclose(fp); 77 OPENSSL_free(e); 78 OPENSSL_free(n); 79 OPENSSL_free(d); 80 OPENSSL_free(ctx); 81 82 return (0); 83 }