SRL Archive - C/C++ Help and Tutorials

Send Data Encrypted with AES256


R0b0t1

2010-06-16 02:03:47

Run `gcc -g3 test.c aes256.c -o test`.

It's pretty simple. You give it whether you wish to listen or send, a host, a port, and a key. If you're running two instances on the same computer, one instance must be told it is sending only; if they're run on different computers starting the program in listen mode will cause the connection to be bi-directional.


./test l localhost 1337 "This is a key."


./test s localhost 1337 "This is a key."

Main program is here in case you didn't want to download a file.
EDIT: Oh, yeah. The aes256 library isn't mine, but I forgot where I got it. It was on my desktop.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <errno.h>

#include <sys/socket.h>
#include <unistd.h>
#include <fcntl.h>
#include <netdb.h>

#include "aes256.h"
#include "isaac.h"

#define PSIZE 256

void cleanup();
void sig_hndl(int sig);

int sockfd;
struct addrinfo *host;
aes256_ctx aes;

int main(int argc, char *argv[])
{
atexit(cleanup);
signal(2, sig_hndl);

if(getaddrinfo(argv[2], argv[3], NULL, &host))
{ puts("FATAL: Error resolving host.");
puts("Usage: [l|s] [host] [port] [key]"); exit(0); }

if((sockfd = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
{ puts("FATAL: Error creating socket."); exit(0); }

//int on = 1;
//if((setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(int))) < 0)
//{ puts("FATAL: Error setting socket options (1)."); exit(0); }

if((fcntl(sockfd, F_SETFD, O_NONBLOCK)) < 0)
{ puts("FATAL: Error setting socket options (2)."); exit(0); }

struct sockaddr_in any;
any.sin_family = AF_INET;
any.sin_addr.s_addr = htonl(INADDR_ANY);
any.sin_port = htons(atoi(argv[3]));
memset(any.sin_zero, 0, sizeof(any.sin_zero));

if(*argv[1] == 'l')
if((bind(sockfd, (struct sockaddr *)&any, sizeof(any))) < 0)
{ puts("FATAL: Error binding socket."); exit(0); }

aes256_init(&aes, argv[4]);

fd_set infd;
FD_ZERO(&infd);
FD_SET(0, &infd);
FD_SET(sockfd, &infd);

while(1)
{
int rlen;
char buf[PSIZE + 1];
memset(buf, 0, PSIZE);

if((select(sockfd + 1, &infd, NULL, NULL, NULL)) < 0)
{ puts("Error in select()."); }

if(FD_ISSET(0, &infd))
{
rlen = read(0, buf, PSIZE);

int i, flen = ((rlen - 1) / 16 + 1);
for(i = 0; i < flen; i++)
aes256_encrypt(&aes, &buf[i * 16]);

if((sendto(sockfd, buf, PSIZE, 0, host->ai_addr, host->ai_addrlen)) < 0)
{ puts("Error sending to remote host."); }
}

if(FD_ISSET(sockfd, &infd))
{
if((rlen = recvfrom(sockfd, buf, PSIZE, 0, host->ai_addr, &host->ai_addrlen)) < 0)
{ puts("Error receiving from remote host."); }

//printf("%d:%s", rlen, buf);

int i, flen = ((rlen - 1) / 16 + 1);
for(i = 0; i < flen; i++)
aes256_decrypt(&aes, &buf[i * 16]);

printf("%s", buf);
}
}

cleanup();
}

void sig_hndl(int sig)
{
puts("");
exit(0);
}

void cleanup()
{
aes256_done(&aes);
close(sockfd);
freeaddrinfo(host);

exit(0);
}