id_to_fp.c 1.7 KB

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