firmware/src/mesh/CryptoEngine.h

62 lines
1.5 KiB
C
Raw Normal View History

2020-05-09 23:15:01 +00:00
#pragma once
#include <Arduino.h>
2021-02-23 02:10:35 +00:00
struct CryptoKey {
uint8_t bytes[32];
/// # of bytes, or -1 to mean "invalid key - do not use"
int8_t length;
};
2020-05-09 23:15:01 +00:00
/**
* see docs/software/crypto.md for details.
*
*/
#define MAX_BLOCKSIZE 256
2020-05-09 23:15:01 +00:00
class CryptoEngine
{
2020-05-10 02:08:04 +00:00
protected:
/** Our per packet nonce */
2022-01-24 07:00:14 +00:00
uint8_t nonce[16] = {0};
2020-05-10 02:08:04 +00:00
2022-01-24 07:00:14 +00:00
CryptoKey key = {};
2021-02-23 02:10:35 +00:00
2020-05-09 23:15:01 +00:00
public:
2020-05-10 02:08:04 +00:00
virtual ~CryptoEngine() {}
2020-05-09 23:15:01 +00:00
/**
* Set the key used for encrypt, decrypt.
*
* As a special case: If all bytes are zero, we assume _no encryption_ and send all data in cleartext.
*
2020-05-10 02:08:04 +00:00
* @param numBytes must be 16 (AES128), 32 (AES256) or 0 (no crypt)
* @param bytes a _static_ buffer that will remain valid for the life of this crypto instance (i.e. this class will cache the
* provided pointer)
2020-05-09 23:15:01 +00:00
*/
2021-02-23 02:10:35 +00:00
virtual void setKey(const CryptoKey &k);
2020-05-09 23:15:01 +00:00
/**
* Encrypt a packet
*
* @param bytes is updated in place
*/
2022-03-20 00:40:13 +00:00
virtual void encrypt(uint32_t fromNode, uint64_t packetId, size_t numBytes, uint8_t *bytes);
virtual void decrypt(uint32_t fromNode, uint64_t packetId, size_t numBytes, uint8_t *bytes);
2020-05-10 02:08:04 +00:00
protected:
/**
* Init our 128 bit nonce for a new packet
*
* The NONCE is constructed by concatenating (from MSB to LSB):
* a 64 bit packet number (stored in little endian order)
* a 32 bit sending node number (stored in little endian order)
* a 32 bit block counter (starts at zero)
*/
2022-03-20 00:40:13 +00:00
void initNonce(uint32_t fromNode, uint64_t packetId);
2020-05-10 02:08:04 +00:00
};
extern CryptoEngine *crypto;