1
0
Fork 0
tetatet/src/main.c

158 lines
3.4 KiB
C

#include <stdio.h>
#include <string.h>
#include "audio.h"
#include "crypt.h"
#include "net.h"
#define CHANNELS 1
#define SAMPLE_RATE 48000
#define FRAMES_PER_BUFFFER 480
#define BUF_SIZE (FRAMES_PER_BUFFFER * CHANNELS)
int main(int argc, char **argv) {
(void)argv;
(void)argc;
if (sodium_init() == -1) {
fprintf(stderr, "A Sodium cryptography library is failed to initialise!\n");
return -1;
}
crypt_key_t own, remote;
if (crypt_key_gen(&own) == -1) {
fprintf(stderr, "Failed to generate the keys.");
return -1;
}
if (crypt_key_gen(&remote) == -1) {
fprintf(stderr, "Failed to generate the keys.");
return -1;
}
unsigned char *oh = crypt_hello(&own);
unsigned char *rh = crypt_hello(&remote);
unsigned char *oc = NULL;
char *rmsg = NULL;
unsigned long long ocl = 0, rml = 0;
int rt = 0;
crypt_session_t os, rs;
unsigned char *nonce_own = NULL, *nonce_rem = NULL;
if (crypt_hello_verify(oh, &own) == -1) {
fprintf(stderr, "oh v fail");
rt = -1;
goto cleanup;
}
if (crypt_hello_verify(rh, &remote) == -1) {
fprintf(stderr, "rh v fail");
rt = -1;
goto cleanup;
}
nonce_own = crypt_hello_get_nonce(oh, rh, false);
nonce_rem = crypt_hello_get_nonce(rh, oh, true);
for (unsigned int i = 0; i < CRYPT_NONCE_LEN; ++i)
if (nonce_own[i] != nonce_rem[i]) {
fprintf(stderr, "A nonce mismatch occured.");
rt = -1;
goto cleanup;
}
if (crypt_session_init(&os, &own, &remote, nonce_own, true) == -1) {
rt = -1;
goto cleanup;
}
if (crypt_session_init(&rs, &remote, &own, nonce_rem, false) == -1) {
rt = -1;
goto cleanup;
}
char msg[] = "Hello!";
unsigned long long msglen = 6;
oc = crypt_session_encrypt(&os, (unsigned char *)msg, msglen, &ocl);
if (oc == NULL) {
fprintf(stderr, "oc is null");
rt = -1;
goto cleanup;
}
rmsg = (char *)crypt_session_decrypt(&rs, oc, ocl, &rml);
if (rmsg == NULL) {
rt = -1;
goto cleanup;
}
if (strcmp(msg, rmsg) != 0)
fprintf(stderr, "Yikes!");
net_t nc, ns;
if (net_client_init(&nc, "127.0.0.1", "14816") == -1) {
rt = -1;
goto cleanup;
}
if (net_server_init(&ns, "127.0.0.1", "14816") == -1) {
rt = -1;
goto cleanup;
}
audio_t aud;
unsigned char buf[BUF_SIZE];
memset(buf, 0, BUF_SIZE);
audio_init(&aud, CHANNELS, SAMPLE_RATE, FRAMES_PER_BUFFFER);
unsigned char *c = NULL, *m = NULL;
unsigned long long cl = 0, ml = 0;
printf("Listening... ");
for (int i = 0; i < (20 * SAMPLE_RATE)/FRAMES_PER_BUFFFER; ++i) {
audio_read(&aud, buf, BUF_SIZE);
c = crypt_session_encrypt(&os, buf, BUF_SIZE, &cl);
int sc = net_send(&nc, (const char *)c, cl);
int rc = net_recv(&ns, c, cl);
fprintf(stderr, "%d %d\n", sc, rc);
m = crypt_session_decrypt(&rs, c, cl, &ml);
audio_write(&aud, m, ml);
free(c); free(m);
}
printf("Done!\n");
audio_destroy(&aud);
cleanup:
free(oh);
free(rh);
free(oc);
free(rmsg);
free(nonce_own);
free(nonce_rem);
crypt_key_destroy(&own);
crypt_key_destroy(&remote);
crypt_session_destroy(&os);
crypt_session_destroy(&rs);
net_destroy(&ns);
net_destroy(&nc);
return rt;
}