The RAK3172_AES
example on my Github is the right place to start. To do what you want, you should do something like this:
• Put the ID of the sender at the beginning. In a simple scheme, one or two bytes should suffice. Say two bytes for now. so buffer[0]
and buffer[1]
contain this ID.
• Next put the recipient’s ID. buffer[2]
and buffer[3]
contain this ID.
• Init an AES context and set up the key:
struct AES_ctx ctx;
AES_init_ctx(&ctx, pKey);
• If you’re using ECB, which I don’t recommend, skip the next step. But do try and use CBC.
• Create an Iv of 16 bytes from a random source. Unfortunately there is no good source on rak3172 – at least until the RUI3 team implements my TRNG recommendation, so for now make it just a new one every time, not sequential, and don’t reuse it. Use something like:
randomSeed(millis());
for (uint8_t ix = 0; ix < 16; ix++) Iv[ix] = random(0, 256);
• Encrypt your plaintext with encryptCBC((uint8_t*)plainBuf, len, Iv);
.
• Copy the Iv to the buffer: memcpy(buffer+4, Iv, 16);
• Copy the ciphertext to the buffer: memcpy(buffer+20, encBuf, len);
• Send the packet (keep in mind the length is len+20
).
When receiving it’s basically the reverse:
• Check payload[2]
and payload[3]
against your ID. If it isn’t, drop and return.
• If it is, init an AES context and set up the key:
struct AES_ctx ctx;
AES_init_ctx(&ctx, pKey);
• Decrypt with decryptCBC(buffer+20, len-20, buffer+4);
===> The Iv is buffer[4-19]
. The ciphertext in buffer[20+]
. The result in decBuf
if you follow the code I posted.
That should get you started.