tor-checkkey.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /* Copyright (c) 2008-2015, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. #include "orconfig.h"
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include "crypto.h"
  7. #include "torlog.h"
  8. #include "util.h"
  9. #include "compat.h"
  10. #include "compat_openssl.h"
  11. #include <openssl/bn.h>
  12. #include <openssl/rsa.h>
  13. int
  14. main(int c, char **v)
  15. {
  16. crypto_pk_t *env;
  17. char *str;
  18. RSA *rsa;
  19. int wantdigest=0;
  20. int fname_idx;
  21. char *fname=NULL;
  22. init_logging(1);
  23. if (c < 2) {
  24. fprintf(stderr, "Hi. I'm tor-checkkey. Tell me a filename that "
  25. "has a PEM-encoded RSA public key (like in a cert) and I'll "
  26. "dump the modulus. Use the --digest option too and I'll "
  27. "dump the digest.\n");
  28. return 1;
  29. }
  30. if (crypto_global_init(0, NULL, NULL)) {
  31. fprintf(stderr, "Couldn't initialize crypto library.\n");
  32. return 1;
  33. }
  34. if (!strcmp(v[1], "--digest")) {
  35. wantdigest = 1;
  36. fname_idx = 2;
  37. if (c<3) {
  38. fprintf(stderr, "too few arguments");
  39. return 1;
  40. }
  41. } else {
  42. wantdigest = 0;
  43. fname_idx = 1;
  44. }
  45. fname = expand_filename(v[fname_idx]);
  46. str = read_file_to_str(fname, 0, NULL);
  47. tor_free(fname);
  48. if (!str) {
  49. fprintf(stderr, "Couldn't read %s\n", v[fname_idx]);
  50. return 1;
  51. }
  52. env = crypto_pk_new();
  53. if (crypto_pk_read_public_key_from_string(env, str, strlen(str))<0) {
  54. fprintf(stderr, "Couldn't parse key.\n");
  55. return 1;
  56. }
  57. tor_free(str);
  58. if (wantdigest) {
  59. char digest[HEX_DIGEST_LEN+1];
  60. if (crypto_pk_get_fingerprint(env, digest, 0)<0)
  61. return 1;
  62. printf("%s\n",digest);
  63. } else {
  64. rsa = crypto_pk_get_rsa_(env);
  65. const BIGNUM *rsa_n;
  66. #ifdef OPENSSL_1_1_API
  67. const BIGNUM *rsa_e, *rsa_d;
  68. RSA_get0_key(rsa, &rsa_n, &rsa_e, &rsa_d);
  69. #else
  70. rsa_n = rsa->n;
  71. #endif
  72. str = BN_bn2hex(rsa_n);
  73. printf("%s\n", str);
  74. }
  75. return 0;
  76. }