romulus/Romulus-M/encrypt_wrapper.c

121 lines
3.2 KiB
C

#include "encrypt_wrapper.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <byteswap.h>
#ifdef _WIN32
#else
#include <sys/random.h>
#endif
#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;
// 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;
// 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};
int ret = romulus_m_encrypt(c, &clen, m, mlen, ad, adlen, 0, &npub[0], &k[0]);
if(clen > *len + CRYPTO_NPUBBYTES || ret != 0){
free(c);
return 1;
}
// type 0 1
// Swap after adding it as additional data
packet->DataType = __bswap_16(packet->DataType);
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);
// Data
// Nonce|Data
// dec
// n = nonce, CRYPTO_NPUBBYTES size 16
unsigned char* npub = &inBuf[loc];
loc += CRYPTO_NPUBBYTES;
// ciphertext - out, MAX 16 bytes larger than plaintext - defined as CRYPTO_ABYTES
int clen = packet->Size - CRYPTO_NPUBBYTES;
unsigned char* c = &inBuf[loc];
// plaintext - in
unsigned long long mlen = clen;
unsigned char* m = (unsigned char*)calloc(mlen, 1);
// additional text
int adlen = sizeof(packet->DataType);
unsigned char* ad = (unsigned char*)&packet->DataType;
// key, CRYPTO_KEYBYTES size 16
unsigned char k[CRYPTO_KEYBYTES] = {0};
int ret = romulus_m_decrypt(m, &mlen, 0, c, clen, ad, adlen, npub, &k[0]);
if(mlen <= 1000 && ret == 0){
memcpy(packet->Data, m, mlen);
packet->Size = (u_int16_t)mlen;
}
else{
free(m);
return 1;
}
free(m);
return 0;
}