supercop

Basic CLI for supercop
git clone git://git.finwo.net/app/supercop
Log | Files | Refs | README | LICENSE

armor.c (1146B)


      1 #include <stdio.h>
      2 #include <string.h>
      3 
      4 #include "armor.h"
      5 
      6 #ifdef __cplusplus
      7 extern "C" {
      8 #endif
      9 
     10 int asc_find_block(const unsigned char *buf, size_t len, const char *label,
     11                    const unsigned char **payload, size_t *payloadlen) {
     12   char begin[64], end[64];
     13   size_t blen, elen, i, pend;
     14   int n;
     15 
     16   if (!buf || !label) return 0;
     17   n = snprintf(begin, sizeof(begin), "-----BEGIN %s-----", label);
     18   if (n < 0 || (size_t)n >= sizeof(begin)) return 0;
     19   n = snprintf(end, sizeof(end), "-----END %s-----", label);
     20   if (n < 0 || (size_t)n >= sizeof(end)) return 0;
     21   blen = strlen(begin);
     22   elen = strlen(end);
     23   if (len < blen) return 0;
     24 
     25   for (i = 0; i + blen <= len; i++) {
     26     size_t pstart;
     27     if (memcmp(buf + i, begin, blen) != 0) continue;
     28     pstart = i + blen;
     29     for (pend = pstart; pend + elen <= len; pend++) {
     30       if (memcmp(buf + pend, end, elen) == 0) {
     31         if (payload) *payload = buf + pstart;
     32         if (payloadlen) *payloadlen = pend - pstart;
     33         return 1;
     34       }
     35     }
     36     // Begin marker without an end: no valid block
     37     return 0;
     38   }
     39   return 0;
     40 }
     41 
     42 #ifdef __cplusplus
     43 } // extern "C"
     44 #endif