pemdecode.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. #include <bio.h>
  12. #include <mp.h>
  13. #include <libsec.h>
  14. void
  15. usage(void)
  16. {
  17. fprint(2, "auth/pemdecode section [file]\n");
  18. exits("usage");
  19. }
  20. void
  21. main(int argc, char **argv)
  22. {
  23. char *buf;
  24. unsigned char *bin;
  25. int fd;
  26. int32_t n, tot;
  27. int len;
  28. char *tag, *file;
  29. ARGBEGIN{
  30. default:
  31. usage();
  32. }ARGEND
  33. if(argc != 1 && argc != 2)
  34. usage();
  35. tag = argv[0];
  36. if(argc == 2)
  37. file = argv[1];
  38. else
  39. file = "#d/0";
  40. if((fd = open(file, OREAD)) < 0)
  41. sysfatal("open %s: %r", file);
  42. buf = nil;
  43. tot = 0;
  44. for(;;){
  45. buf = realloc(buf, tot+8192);
  46. if(buf == nil)
  47. sysfatal("realloc: %r");
  48. if((n = read(fd, buf+tot, 8192)) < 0)
  49. sysfatal("read: %r");
  50. if(n == 0)
  51. break;
  52. tot += n;
  53. }
  54. buf[tot] = 0;
  55. bin = decodePEM(buf, tag, &len, nil);
  56. if(bin == nil)
  57. sysfatal("cannot extract section '%s' from pem", tag);
  58. if((n=write(1, bin, len)) != len)
  59. sysfatal("writing %d bytes got %ld: %r", len, n);
  60. exits(0);
  61. }