key.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /**
  2. * key.c
  3. * Key management.
  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.5 2002/03/12 23:28:26 mp292
  14. * Removed calls to ERR_load_crypto_strings() (libcrypt).
  15. *
  16. * Revision 1.4 2002/01/27 19:23:03 mp292
  17. * Fixed a bug in parameter checking.
  18. *
  19. * Revision 1.3 2002/01/26 18:50:11 mp292
  20. * Reviewed according to Secure-Programs-HOWTO.
  21. *
  22. * Revision 1.2 2002/01/04 07:19:03 badbytes
  23. * Key generation moved to a separate utility (orkeygen).
  24. *
  25. * Revision 1.1 2001/12/14 12:16:33 badbytes
  26. * Added routine for reading a private key from a file.
  27. *
  28. */
  29. #include <string.h>
  30. #include <openssl/err.h>
  31. #include <openssl/pem.h>
  32. #include "key.h"
  33. #include "log.h"
  34. #include "config.h"
  35. RSA *load_prkey(unsigned char *keyfile)
  36. {
  37. RSA *rsa_private=NULL;
  38. FILE *f_pr;
  39. int retval = 0;
  40. if (keyfile) /* non-NULL filename */
  41. {
  42. if (strspn(keyfile,CONFIG_LEGAL_FILENAME_CHARACTERS) == strlen(keyfile)) /* filename contains legal characters only */
  43. {
  44. /* open the keyfile */
  45. f_pr=fopen(keyfile,"r");
  46. if (!f_pr)
  47. {
  48. log(LOG_ERR,"Failed to open keyfile %s.",keyfile);
  49. return NULL;
  50. }
  51. /* read the private key */
  52. rsa_private = PEM_read_RSAPrivateKey(f_pr,&rsa_private,NULL,NULL);
  53. fclose(f_pr);
  54. if (!rsa_private)
  55. {
  56. log(LOG_ERR,"Error reading private key : %s",ERR_reason_error_string(ERR_get_error()));
  57. return NULL;
  58. }
  59. /* check the private key */
  60. retval = RSA_check_key(rsa_private);
  61. if (retval == 0)
  62. {
  63. log(LOG_ERR,"Private key read but is invalid : %s.", ERR_reason_error_string(ERR_get_error()));
  64. RSA_free(rsa_private);
  65. return NULL;
  66. }
  67. else if (retval == -1)
  68. {
  69. log(LOG_ERR,"Private key read but validity checking failed : %s",ERR_reason_error_string(ERR_get_error()));
  70. RSA_free(rsa_private);
  71. return NULL;
  72. }
  73. else if (retval == 1)
  74. {
  75. return rsa_private;
  76. }
  77. } /* filename contains legal characters only */
  78. }
  79. return NULL; /* report error */
  80. }