decodepem.c 1.8 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 <mp.h>
  12. #include <libsec.h>
  13. #define STRLEN(s) (sizeof(s)-1)
  14. uint8_t*
  15. decodepem(int8_t *s, int8_t *type, int *len)
  16. {
  17. uint8_t *d;
  18. int8_t *t, *e, *tt;
  19. int n;
  20. /*
  21. * find the correct section of the file, stripping garbage at the beginning and end.
  22. * the data is delimited by -----BEGIN <type>-----\n and -----END <type>-----\n
  23. */
  24. n = strlen(type);
  25. e = strchr(s, '\0');
  26. for(t = s; t != nil && t < e; ){
  27. tt = t;
  28. t = strchr(tt, '\n');
  29. if(t != nil)
  30. t++;
  31. if(strncmp(tt, "-----BEGIN ", STRLEN("-----BEGIN ")) == 0
  32. && strncmp(&tt[STRLEN("-----BEGIN ")], type, n) == 0
  33. && strncmp(&tt[STRLEN("-----BEGIN ")+n], "-----\n", STRLEN("-----\n")) == 0)
  34. break;
  35. }
  36. for(tt = t; tt != nil && tt < e; tt++){
  37. if(strncmp(tt, "-----END ", STRLEN("-----END ")) == 0
  38. && strncmp(&tt[STRLEN("-----END ")], type, n) == 0
  39. && strncmp(&tt[STRLEN("-----END ")+n], "-----\n", STRLEN("-----\n")) == 0)
  40. break;
  41. tt = strchr(tt, '\n');
  42. if(tt == nil)
  43. break;
  44. }
  45. if(tt == nil || tt == e){
  46. werrstr("incorrect .pem file format: bad header or trailer");
  47. return nil;
  48. }
  49. n = ((tt - t) * 6 + 7) / 8;
  50. d = malloc(n);
  51. if(d == nil){
  52. werrstr("out of memory");
  53. return nil;
  54. }
  55. n = dec64(d, n, t, tt - t);
  56. if(n < 0){
  57. free(d);
  58. werrstr("incorrect .pem file format: bad base64 encoded data");
  59. return nil;
  60. }
  61. *len = n;
  62. return d;
  63. }