2020-05-09 19:08:04 -07:00
|
|
|
#include "CryptoEngine.h"
|
|
|
|
|
#include "configuration.h"
|
|
|
|
|
|
2022-09-03 23:38:40 +08:00
|
|
|
#include "mbedtls/aes.h"
|
2022-09-09 22:31:30 +02:00
|
|
|
|
2020-05-09 19:08:04 -07:00
|
|
|
class ESP32CryptoEngine : public CryptoEngine
|
|
|
|
|
{
|
|
|
|
|
|
|
|
|
|
mbedtls_aes_context aes;
|
|
|
|
|
|
|
|
|
|
public:
|
|
|
|
|
ESP32CryptoEngine() { mbedtls_aes_init(&aes); }
|
|
|
|
|
|
|
|
|
|
~ESP32CryptoEngine() { mbedtls_aes_free(&aes); }
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Encrypt a packet
|
|
|
|
|
*
|
|
|
|
|
* @param bytes is updated in place
|
2024-08-10 22:38:05 -05:00
|
|
|
* TODO: return bool, and handle graciously when something fails
|
2020-05-09 19:08:04 -07:00
|
|
|
*/
|
2024-08-10 22:38:05 -05:00
|
|
|
virtual void encryptAESCtr(CryptoKey _key, uint8_t *_nonce, size_t numBytes, uint8_t *bytes) override
|
2020-05-09 19:08:04 -07:00
|
|
|
{
|
2024-08-10 22:38:05 -05:00
|
|
|
if (_key.length > 0) {
|
2023-01-07 15:24:46 +01:00
|
|
|
if (numBytes <= MAX_BLOCKSIZE) {
|
2024-08-10 22:38:05 -05:00
|
|
|
mbedtls_aes_setkey_enc(&aes, _key.bytes, _key.length * 8);
|
2023-01-07 15:24:46 +01:00
|
|
|
static uint8_t scratch[MAX_BLOCKSIZE];
|
2023-01-07 15:43:17 +01:00
|
|
|
uint8_t stream_block[16];
|
|
|
|
|
size_t nc_off = 0;
|
2023-01-07 15:24:46 +01:00
|
|
|
memcpy(scratch, bytes, numBytes);
|
|
|
|
|
memset(scratch + numBytes, 0,
|
2023-01-21 14:34:29 +01:00
|
|
|
sizeof(scratch) - numBytes); // Fill rest of buffer with zero (in case cypher looks at it)
|
2024-08-10 22:38:05 -05:00
|
|
|
mbedtls_aes_crypt_ctr(&aes, numBytes, &nc_off, _nonce, stream_block, scratch, bytes);
|
2023-01-07 15:24:46 +01:00
|
|
|
} else {
|
|
|
|
|
LOG_ERROR("Packet too large for crypto engine: %d. noop encryption!\n", numBytes);
|
|
|
|
|
}
|
2020-05-09 19:08:04 -07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2024-08-10 22:38:05 -05:00
|
|
|
CryptoEngine *crypto = new ESP32CryptoEngine();
|