Blob


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