trust.c (2064B)
1 #include "trust.h" 2 3 #include <stdio.h> 4 #include <string.h> 5 6 #include "b64.h" 7 8 #define KEYID_HEX_LEN (2u * DIST_KEYID_LEN) 9 10 int dist_trust_lookup(const uint8_t* file, size_t len, 11 const uint8_t keyid[DIST_KEYID_LEN], 12 uint8_t pk[DIST_ED25519_PK_LEN]) { 13 size_t pos = 0; 14 while (pos < len) { 15 char line[DIST_TRUST_LINE_MAX]; 16 size_t start = pos, end = pos, n; 17 char *p, *sp; 18 uint8_t got_id[DIST_KEYID_LEN]; 19 20 while (end < len && file[end] != '\n') ++end; 21 n = end - start; 22 pos = (end < len) ? end + 1 : end; 23 if (n == 0 || n >= sizeof line) continue; 24 memcpy(line, file + start, n); 25 line[n] = '\0'; 26 27 p = line; 28 while (*p == ' ' || *p == '\t') ++p; 29 if (*p == '\0' || *p == '#') continue; 30 31 /* First token: key id (hex). */ 32 sp = strchr(p, ' '); 33 if (!sp) continue; 34 *sp = '\0'; 35 if (strlen(p) != KEYID_HEX_LEN) continue; 36 if (dist_hex_decode(got_id, p, DIST_KEYID_LEN) != DIST_OK) continue; 37 if (memcmp(got_id, keyid, DIST_KEYID_LEN) != 0) continue; 38 39 /* Second token: base64 public key. */ 40 p = sp + 1; 41 while (*p == ' ' || *p == '\t') ++p; 42 sp = strchr(p, ' '); 43 if (sp) *sp = '\0'; 44 { 45 uint8_t buf[DIST_ED25519_PK_LEN + 4]; 46 size_t got = 0; 47 if (dist_b64_decode(buf, &got, p, strlen(p)) != DIST_OK) return DIST_ERR; 48 if (got != DIST_ED25519_PK_LEN) return DIST_ERR; 49 memcpy(pk, buf, DIST_ED25519_PK_LEN); 50 return DIST_OK; 51 } 52 } 53 return DIST_ERR; 54 } 55 56 int dist_trust_format_entry(char* out, size_t cap, 57 const uint8_t keyid[DIST_KEYID_LEN], 58 const uint8_t pk[DIST_ED25519_PK_LEN], 59 const char* label) { 60 char hex[KEYID_HEX_LEN + 1]; 61 char b64[DIST_B64_ENCODED_CAP(DIST_ED25519_PK_LEN)]; 62 int n; 63 dist_hex_encode(hex, keyid, DIST_KEYID_LEN); 64 dist_b64_encode(b64, pk, DIST_ED25519_PK_LEN); 65 n = snprintf(out, cap, "%s %s %s\n", hex, b64, label ? label : ""); 66 return (n > 0 && (size_t)n < cap) ? DIST_OK : DIST_ERR; 67 }