pemdecode.c 947 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <bio.h>
  4. #include <mp.h>
  5. #include <libsec.h>
  6. void
  7. usage(void)
  8. {
  9. fprint(2, "auth/pemdecode section [file]\n");
  10. exits("usage");
  11. }
  12. void
  13. main(int argc, char **argv)
  14. {
  15. char *buf;
  16. uchar *bin;
  17. int fd;
  18. long n, tot;
  19. int len;
  20. char *tag, *file;
  21. ARGBEGIN{
  22. default:
  23. usage();
  24. }ARGEND
  25. if(argc != 1 && argc != 2)
  26. usage();
  27. tag = argv[0];
  28. if(argc == 2)
  29. file = argv[1];
  30. else
  31. file = "#d/0";
  32. if((fd = open(file, OREAD)) < 0)
  33. sysfatal("open %s: %r", file);
  34. buf = nil;
  35. tot = 0;
  36. for(;;){
  37. buf = realloc(buf, tot+8192);
  38. if(buf == nil)
  39. sysfatal("realloc: %r");
  40. if((n = read(fd, buf+tot, 8192)) < 0)
  41. sysfatal("read: %r");
  42. if(n == 0)
  43. break;
  44. tot += n;
  45. }
  46. buf[tot] = 0;
  47. bin = decodePEM(buf, tag, &len, nil);
  48. if(bin == nil)
  49. sysfatal("cannot extract section '%s' from pem", tag);
  50. if((n=write(1, bin, len)) != len)
  51. sysfatal("writing %d bytes got %ld: %r", len, n);
  52. exits(0);
  53. }