orkeygen.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. /**
  2. * orkeygen.c
  3. * Key generation utility.
  4. *
  5. * Matej Pfajfar <mp292@cam.ac.uk>
  6. */
  7. /*
  8. * Changes :
  9. * $Log$
  10. * Revision 1.1 2002/06/26 22:45:50 arma
  11. * Initial revision
  12. *
  13. * Revision 1.1 2002/01/04 07:19:27 badbytes
  14. * Key generation utility.
  15. *
  16. *
  17. */
  18. #include <stdlib.h>
  19. #include <stdio.h>
  20. #include <openssl/rsa.h>
  21. #include <openssl/err.h>
  22. #include <openssl/pem.h>
  23. int main(int argc, char *argv[])
  24. {
  25. char *file_pr = argv[1];
  26. char *file_pu = argv[2];
  27. FILE *f_pr = NULL;
  28. FILE *f_pu = NULL;
  29. RSA *rsa_key = NULL;
  30. int retval = 0;
  31. if (argc < 3)
  32. {
  33. printf("Need two files, for private and public key in that order.\n");
  34. exit(1);
  35. }
  36. /* generate the key */
  37. rsa_key = RSA_generate_key(1024,65535,NULL,NULL);
  38. if (!rsa_key) /* error has occured */
  39. {
  40. printf("%s",ERR_reason_error_string(ERR_get_error()));
  41. exit(1);
  42. }
  43. else /* keys generated */
  44. {
  45. retval = RSA_check_key(rsa_key);
  46. if (retval == 1)
  47. {
  48. printf("Generated key seems to be valid.\n");
  49. /* open the output files */
  50. f_pr = fopen(file_pr,"w");
  51. if (!f_pr)
  52. {
  53. perror("fopen");
  54. RSA_free(rsa_key);
  55. exit(1);
  56. }
  57. f_pu = fopen(file_pu,"w");
  58. if (!f_pu)
  59. {
  60. perror("fopen");
  61. RSA_free(rsa_key);
  62. exit(1);
  63. }
  64. /* write the private key */
  65. retval = PEM_write_RSAPrivateKey(f_pr,rsa_key,NULL,NULL,0,0,NULL);
  66. if (retval == 0)
  67. {
  68. printf("%s",ERR_reason_error_string(ERR_get_error()));
  69. fclose(f_pr);
  70. fclose(f_pu);
  71. RSA_free(rsa_key);
  72. exit(1);
  73. }
  74. /* write the public key */
  75. retval = PEM_write_RSAPublicKey(f_pu,rsa_key);
  76. if (retval == 0)
  77. {
  78. printf("%s",ERR_reason_error_string(ERR_get_error()));
  79. fclose(f_pr);
  80. fclose(f_pu);
  81. RSA_free(rsa_key);
  82. exit(1);
  83. }
  84. printf("Keys written to files %s (public) and %s (private).\n",file_pu,file_pr);
  85. }
  86. else if (retval == 0)
  87. {
  88. printf("Generated key seems to be invalid. Exiting.\n");
  89. RSA_free(rsa_key);
  90. exit(1);
  91. }
  92. else if (retval == -1)
  93. {
  94. printf("%s",ERR_reason_error_string(ERR_get_error()));
  95. RSA_free(rsa_key);
  96. exit(1);
  97. }
  98. }
  99. RSA_free(rsa_key);
  100. fclose(f_pu);
  101. fclose(f_pr);
  102. exit(0);
  103. }