readcert.c 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <auth.h>
  4. #include <mp.h>
  5. #include <libsec.h>
  6. static char*
  7. readfile(char *name)
  8. {
  9. int fd;
  10. char *s;
  11. Dir *d;
  12. fd = open(name, OREAD);
  13. if(fd < 0)
  14. return nil;
  15. if((d = dirfstat(fd)) == nil)
  16. return nil;
  17. s = malloc(d->length + 1);
  18. if(s == nil || readn(fd, s, d->length) != d->length){
  19. free(s);
  20. free(d);
  21. close(fd);
  22. return nil;
  23. }
  24. close(fd);
  25. s[d->length] = '\0';
  26. free(d);
  27. return s;
  28. }
  29. uchar*
  30. readcert(char *filename, int *pcertlen)
  31. {
  32. char *pem;
  33. uchar *binary;
  34. pem = readfile(filename);
  35. if(pem == nil){
  36. werrstr("can't read %s", filename);
  37. return nil;
  38. }
  39. binary = decodePEM(pem, "CERTIFICATE", pcertlen, nil);
  40. free(pem);
  41. if(binary == nil){
  42. werrstr("can't parse %s", filename);
  43. return nil;
  44. }
  45. return binary;
  46. }
  47. PEMChain *
  48. readcertchain(char *filename)
  49. {
  50. char *chfile;
  51. PEMChain *chp;
  52. chfile = readfile(filename);
  53. if (chfile == nil) {
  54. werrstr("can't read %s", filename);
  55. return nil;
  56. }
  57. chp = decodepemchain(chfile, "CERTIFICATE");
  58. return chp;
  59. }