Files
firmware/src/platform/esp32/ESP32CryptoEngine.cpp

41 lines
1.3 KiB
C++
Raw Normal View History

2020-05-09 19:08:04 -07:00
#include "CryptoEngine.h"
#include "configuration.h"
#include "mbedtls/aes.h"
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
* TODO: return bool, and handle graciously when something fails
2020-05-09 19:08:04 -07:00
*/
virtual void encryptAESCtr(CryptoKey _key, uint8_t *_nonce, size_t numBytes, uint8_t *bytes) override
2020-05-09 19:08:04 -07:00
{
if (_key.length > 0) {
2023-01-07 15:24:46 +01:00
if (numBytes <= MAX_BLOCKSIZE) {
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)
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
}
}
};
CryptoEngine *crypto = new ESP32CryptoEngine();