Make an attempt to fix bug 1024.
[tor/rransom.git] / contrib / id_to_fp.c
blob73395e16c128c650da93c777337be8cf7cb0fab3
1 /* Copyright 2006 Nick Mathewson; see LICENSE for licensing information */
2 /* $Id$ */
4 /* id_to_fp.c : Helper for directory authority ops. When somebody sends us
5 * a private key, this utility converts the private key into a fingerprint
6 * so you can de-list that fingerprint.
7 */
9 #include <openssl/rsa.h>
10 #include <openssl/bio.h>
11 #include <openssl/sha.h>
12 #include <openssl/pem.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
18 #define die(s) do { fprintf(stderr, "%s\n", s); goto err; } while (0)
20 int
21 main(int argc, char **argv)
23 BIO *b = NULL;
24 RSA *key = NULL;
25 unsigned char *buf = NULL, *bufp;
26 int len, i;
27 unsigned char digest[20];
28 int status = 1;
30 if (argc < 2) {
31 fprintf(stderr, "Reading key from stdin...\n");
32 if (!(b = BIO_new_fp(stdin, BIO_NOCLOSE)))
33 die("couldn't read from stdin");
34 } else if (argc == 2) {
35 if (strcmp(argv[1], "-h") == 0 ||
36 strcmp(argv[1], "--help") == 0) {
37 fprintf(stdout, "Usage: %s [keyfile]\n", argv[0]);
38 status = 0;
39 goto err;
40 } else {
41 if (!(b = BIO_new_file(argv[1], "r")))
42 die("couldn't open file");
44 } else {
45 fprintf(stderr, "Usage: %s [keyfile]\n", argv[0]);
46 goto err;
48 if (!(key = PEM_read_bio_RSAPrivateKey(b, NULL, NULL, NULL)))
49 die("couldn't parse key");
51 len = i2d_RSAPublicKey(key, NULL);
52 if (len < 0)
53 die("Bizarre key");
54 bufp = buf = malloc(len+1);
55 if (!buf)
56 die("Out of memory");
57 len = i2d_RSAPublicKey(key, &bufp);
58 if (len < 0)
59 die("Bizarre key");
61 SHA1(buf, len, digest);
62 for (i=0; i < 20; i += 2) {
63 printf("%02X%02X ", (int)digest[i], (int)digest[i+1]);
65 printf("\n");
67 status = 0;
69 err:
70 if (buf)
71 free(buf);
72 if (key)
73 RSA_free(key);
74 if (b)
75 BIO_free(b);
76 return status;