pemencode.c 998 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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, *cbuf;
  16. int fd;
  17. long n, tot;
  18. int len;
  19. char *tag, *file;
  20. ARGBEGIN{
  21. default:
  22. usage();
  23. }ARGEND
  24. if(argc != 1 && argc != 2)
  25. usage();
  26. tag = argv[0];
  27. if(argc == 2)
  28. file = argv[1];
  29. else
  30. file = "#d/0";
  31. if((fd = open(file, OREAD)) < 0)
  32. sysfatal("open %s: %r", file);
  33. buf = nil;
  34. tot = 0;
  35. for(;;){
  36. buf = realloc(buf, tot+8192);
  37. if(buf == nil)
  38. sysfatal("realloc: %r");
  39. if((n = read(fd, buf+tot, 8192)) < 0)
  40. sysfatal("read: %r");
  41. if(n == 0)
  42. break;
  43. tot += n;
  44. }
  45. buf[tot] = 0;
  46. cbuf = malloc(2*tot);
  47. if(cbuf == nil)
  48. sysfatal("malloc: %r");
  49. len = enc64(cbuf, 2*tot, (uchar*)buf, tot);
  50. print("-----BEGIN %s-----\n", tag);
  51. while(len > 0){
  52. print("%.64s\n", cbuf);
  53. cbuf += 64;
  54. len -= 64;
  55. }
  56. print("-----END %s-----\n", tag);
  57. exits(0);
  58. }