supercop

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

encode.c (1168B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <string.h>
      4 
      5 #include "common.h"
      6 
      7 #ifdef __cplusplus
      8 extern "C" {
      9 #endif
     10 
     11 static void hdr_hex_encode(char *dst, const unsigned char *src, size_t n) {
     12   static const char digits[] = "0123456789abcdef";
     13   size_t i;
     14   for (i = 0; i < n; i++) {
     15     dst[i * 2]     = digits[(src[i] >> 4) & 0xF];
     16     dst[i * 2 + 1] = digits[src[i] & 0xF];
     17   }
     18   dst[n * 2] = '\0';
     19 }
     20 
     21 char * fmt_hdr_encode(struct KeyPair *kp, size_t *len) {
     22   char pubhex[65];
     23   char privhex[129];
     24   const char *privstr;
     25   char *out;
     26   size_t need;
     27   int n;
     28 
     29   if (!kp || !kp->public_key || !len) return NULL;
     30   hdr_hex_encode(pubhex, kp->public_key, 32);
     31   if (kp->private_key) {
     32     hdr_hex_encode(privhex, kp->private_key, 64);
     33     privstr = privhex;
     34   } else {
     35     privstr = "(no private key)";
     36   }
     37 
     38   need = strlen("public-key: \nprivate-key: \n") + 64 + strlen(privstr) + 1;
     39   out = malloc(need);
     40   if (!out) return NULL;
     41   n = snprintf(out, need, "public-key: %s\nprivate-key: %s\n", pubhex, privstr);
     42   if (n < 0 || (size_t)n >= need) {
     43     free(out);
     44     return NULL;
     45   }
     46   *len = (size_t)n;
     47   return out;
     48 }
     49 
     50 #ifdef __cplusplus
     51 } // extern "C"
     52 #endif