charm
charm copied to clipboard
Minimal code example for us noobs?
I struggled to grok how state I was supposed to managed state between lib calls. I realized that state needs to be fully managed between two peers which seems obvious, but I guess for those just looking to play with the library and see how it works it's not. Anyway I have this short working code example that I would like to find a home for here if at all possible, thanks.
#include "charm.h"
#include <stdio.h>
#include <string.h>
#define TAG_LEN 6 // not sure why this is here but it's used here https://github.com/fengjijiao/dsvpn/blob/19c9d6612ea29cb9796484a9a62b0f31ca8d42f3/include/vpn.h#L46
#define SHARED_CONTEXT "my code example"
#define SHARED_KEY "0my0secret0key0ayy0lmaooo0:)0000"
void printBytes(unsigned char *bb, size_t len) {
for (void *end = &bb[len]; bb != end; bb++)
printf("\\x%02x", *bb);
}
int main(int argc, char *argv[]) {
// Show message.
unsigned char msg[6] = "hello";
printf("msg\n");
printBytes(msg, sizeof msg);
printf("\n");
unsigned char tag_full[16];
// Encrypt.
{
uint32_t st[12];
unsigned char key[32] = SHARED_KEY;
uint8_t iv[16] = SHARED_CONTEXT;
uc_state_init(st, key, iv);
uc_encrypt(st, (unsigned char *)msg, sizeof msg, tag_full);
printf("encrypted msg\n");
printBytes(msg, sizeof msg);
printf("\n");
}
// Decrypt.
{
uint32_t st[12];
unsigned char key[32] = SHARED_KEY;
uint8_t iv[16] = SHARED_CONTEXT;
unsigned char tag[TAG_LEN];
uc_state_init(st, key, iv);
memcpy(tag, tag_full, TAG_LEN);
if (uc_decrypt(st, (unsigned char *)msg, sizeof msg, tag, sizeof(tag)) != 0) {
fprintf(stderr, "failed to decrypt\n");
exit(1);
}
printf("decrypted msg\n");
printBytes(msg, 6);
printf("\n");
}
return 0;
}