97 lines
2.4 KiB
C
97 lines
2.4 KiB
C
|
#include "encrypt_wrapper.h"
|
||
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <string.h>
|
||
|
#include <byteswap.h>
|
||
|
#include <sys/random.h>
|
||
|
#include "romulus_m.h"
|
||
|
#include "api.h"
|
||
|
|
||
|
|
||
|
int encrypt(packet *packet, unsigned char* outBuf, __uint16_t *len){
|
||
|
if(sizeof(u_int16_t) + sizeof(u_int16_t) + packet->Size > *len){
|
||
|
return 1;
|
||
|
}
|
||
|
|
||
|
int packetSize = packet->Size;
|
||
|
|
||
|
packet->DataType = __bswap_16(packet->DataType);
|
||
|
|
||
|
// enc
|
||
|
// ciphertext - out, MAX 16 bytes larger than plaintext - defined as CRYPTO_ABYTES
|
||
|
unsigned long long clen = packetSize + CRYPTO_ABYTES;
|
||
|
unsigned char* c = (unsigned char*) calloc(clen, 1);
|
||
|
|
||
|
// plaintext - in
|
||
|
int mlen = packetSize;
|
||
|
unsigned char* m = packet->Data;
|
||
|
|
||
|
|
||
|
// additional text
|
||
|
int adlen = sizeof(packet->DataType);
|
||
|
unsigned char* ad = (unsigned char*)&packet->DataType;
|
||
|
|
||
|
// unused
|
||
|
unsigned char* nsec;
|
||
|
|
||
|
// n = nonce, CRYPTO_NPUBBYTES size 16
|
||
|
unsigned char npub[CRYPTO_NPUBBYTES];
|
||
|
getrandom(&npub[0], sizeof(npub), 0);
|
||
|
|
||
|
// key, CRYPTO_KEYBYTES size 16
|
||
|
unsigned char k[CRYPTO_KEYBYTES] = {0};
|
||
|
romulus_m_encrypt(c, &clen, m, mlen, ad, adlen, 0, &npub[0], &k[0]);
|
||
|
|
||
|
if(clen > *len + CRYPTO_NPUBBYTES){
|
||
|
free(c);
|
||
|
return 1;
|
||
|
}
|
||
|
|
||
|
// type 0 1
|
||
|
int loc = 0;
|
||
|
memcpy(&outBuf[loc], &packet->DataType,sizeof(u_int16_t));
|
||
|
loc += sizeof(u_int16_t);
|
||
|
|
||
|
// data size 2 3
|
||
|
u_int16_t clen16 = (u_int16_t)clen;
|
||
|
// we copy data and nonce
|
||
|
clen16 += CRYPTO_NPUBBYTES;
|
||
|
clen16 = __bswap_16(clen16);
|
||
|
memcpy(&outBuf[loc], &clen16, sizeof(u_int16_t));
|
||
|
loc += sizeof(u_int16_t);
|
||
|
|
||
|
memcpy(&outBuf[loc], npub, CRYPTO_NPUBBYTES);
|
||
|
loc += CRYPTO_NPUBBYTES;
|
||
|
|
||
|
memcpy(&outBuf[loc], c, clen);
|
||
|
loc += clen;
|
||
|
|
||
|
*len = loc;
|
||
|
|
||
|
free(c);
|
||
|
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
int decrypt(packetEx *packet, unsigned char* inBuf, __uint16_t len){
|
||
|
int loc = 0;
|
||
|
memcpy(&packet->DataType, &inBuf[loc], sizeof(u_int16_t));
|
||
|
loc += sizeof(u_int16_t);
|
||
|
memcpy(&packet->Id, &inBuf[loc], sizeof(u_int32_t));
|
||
|
loc += sizeof(u_int32_t);
|
||
|
memcpy(&packet->Size, &inBuf[loc], sizeof(u_int16_t));
|
||
|
loc += sizeof(u_int16_t);
|
||
|
|
||
|
packet->DataType = __bswap_16(packet->DataType);
|
||
|
packet->Size = __bswap_16(packet->Size);
|
||
|
packet->Id = __bswap_32(packet->Id);
|
||
|
|
||
|
if(packet->Size <= 1000){
|
||
|
memcpy(packet->Data, &inBuf[loc], packet->Size);
|
||
|
}
|
||
|
else{
|
||
|
return 1;
|
||
|
}
|
||
|
|
||
|
return 0;
|
||
|
}
|