new cspot/bell

This commit is contained in:
philippe44
2023-05-06 23:50:26 +02:00
parent e0e7e718ba
commit 8bad480112
163 changed files with 6611 additions and 6739 deletions

View File

@@ -1,120 +1,140 @@
#ifndef BELL_LOGGER_H
#define BELL_LOGGER_H
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <string>
#include <memory>
#include <stdarg.h> // for va_end, va_list, va_start
#include <stdio.h> // for printf, vprintf
#include <chrono>
#include <iomanip>
#include <iostream>
#include <string> // for string, basic_string
namespace bell
{
namespace bell {
class AbstractLogger
{
public:
bool enableSubmodule = false;
virtual void debug(std::string filename, int line, std::string submodule, const char *format, ...) = 0;
virtual void error(std::string filename, int line, std::string submodule, const char *format, ...) = 0;
virtual void info(std::string filename, int line, std::string submodule, const char *format, ...) = 0;
};
class AbstractLogger {
public:
bool enableSubmodule = false;
bool enableTimestamp = false;
extern bell::AbstractLogger* bellGlobalLogger;
class BellLogger : public bell::AbstractLogger
{
public:
// static bool enableColors = true;
void debug(std::string filename, int line, std::string submodule, const char *format, ...)
{
virtual void debug(std::string filename, int line, std::string submodule,
const char* format, ...) = 0;
virtual void error(std::string filename, int line, std::string submodule,
const char* format, ...) = 0;
virtual void info(std::string filename, int line, std::string submodule,
const char* format, ...) = 0;
};
printf(colorRed);
printf("D ");
if (enableSubmodule) {
printf(colorReset);
printf("[%s] ", submodule.c_str());
}
printFilename(filename);
printf(":%d: ", line);
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
printf("\n");
};
extern bell::AbstractLogger* bellGlobalLogger;
class BellLogger : public bell::AbstractLogger {
public:
// static bool enableColors = true;
void debug(std::string filename, int line, std::string submodule,
const char* format, ...) {
printTimestamp();
void error(std::string filename, int line, std::string submodule, const char *format, ...)
{
printf(colorRed);
printf("D ");
if (enableSubmodule) {
printf(colorReset);
printf("[%s] ", submodule.c_str());
}
printFilename(filename);
printf(":%d: ", line);
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
printf("\n");
};
printf(colorRed);
printf("E ");
if (enableSubmodule) {
printf(colorReset);
printf("[%s] ", submodule.c_str());
}
printFilename(filename);
printf(":%d: ", line);
printf(colorRed);
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
printf("\n");
};
void error(std::string filename, int line, std::string submodule,
const char* format, ...) {
printTimestamp();
void info(std::string filename, int line, std::string submodule, const char *format, ...)
{
printf(colorRed);
printf("E ");
if (enableSubmodule) {
printf(colorReset);
printf("[%s] ", submodule.c_str());
}
printFilename(filename);
printf(":%d: ", line);
printf(colorRed);
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
printf("\n");
};
printf(colorBlue);
printf("I ");
if (enableSubmodule) {
printf(colorReset);
printf("[%s] ", submodule.c_str());
}
printFilename(filename);
printf(":%d: ", line);
printf(colorReset);
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
printf("\n");
};
void info(std::string filename, int line, std::string submodule,
const char* format, ...) {
printTimestamp();
void printFilename(std::string filename)
{
printf(colorBlue);
printf("I ");
if (enableSubmodule) {
printf(colorReset);
printf("[%s] ", submodule.c_str());
}
printFilename(filename);
printf(":%d: ", line);
printf(colorReset);
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
printf("\n");
};
void printTimestamp() {
if (enableTimestamp) {
auto now = std::chrono::system_clock::now();
time_t now_time = std::chrono::system_clock::to_time_t(now);
const auto nowMs = std::chrono::duration_cast<std::chrono::milliseconds>(
now.time_since_epoch()) %
1000;
auto gmt_time = gmtime(&now_time);
printf(colorReset);
std::cout << std::put_time(gmt_time, "[%Y-%m-%d %H:%M:%S") << '.'
<< std::setfill('0') << std::setw(3) << nowMs.count() << "] ";
}
}
void printFilename(std::string filename) {
#ifdef _WIN32
std::string basenameStr(filename.substr(filename.rfind("\\") + 1));
std::string basenameStr(filename.substr(filename.rfind("\\") + 1));
#else
std::string basenameStr(filename.substr(filename.rfind("/") + 1));
std::string basenameStr(filename.substr(filename.rfind("/") + 1));
#endif
unsigned long hash = 5381;
for (char const &c : basenameStr)
{
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
}
unsigned long hash = 5381;
for (char const& c : basenameStr) {
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
}
printf("\033[0;%dm", allColors[hash % NColors]);
printf("\033[0;%dm", allColors[hash % NColors]);
printf("%s", basenameStr.c_str());
printf(colorReset);
}
printf("%s", basenameStr.c_str());
printf(colorReset);
}
private:
static constexpr const char *colorReset = "\033[0m";
static constexpr const char *colorRed = "\033[0;31m";
static constexpr const char *colorBlue = "\033[0;34m";
static constexpr const int NColors = 15;
static constexpr int allColors[NColors] = {31, 32, 33, 34, 35, 36, 37, 90, 91, 92, 93, 94, 95, 96, 97};
};
private:
static constexpr const char* colorReset = "\033[0m";
static constexpr const char* colorRed = "\033[0;31m";
static constexpr const char* colorBlue = "\033[0;34m";
static constexpr const int NColors = 15;
static constexpr int allColors[NColors] = {31, 32, 33, 34, 35, 36, 37, 90,
91, 92, 93, 94, 95, 96, 97};
};
void setDefaultLogger();
void enableSubmoduleLogging();
}
void setDefaultLogger();
void enableSubmoduleLogging();
void enableTimestampLogging();
} // namespace bell
#define BELL_LOG(type, ...) \
do \
{ \
bell::bellGlobalLogger->type(__FILE__, __LINE__, __VA_ARGS__); \
} while (0)
#define BELL_LOG(type, ...) \
do { \
bell::bellGlobalLogger->type(__FILE__, __LINE__, __VA_ARGS__); \
} while (0)
#endif
#endif

View File

@@ -15,8 +15,8 @@
#include <pthread.h>
#endif
#include <string>
#include <iostream>
#include <string>
namespace bell {
class Task {

View File

@@ -1,14 +1,16 @@
#ifndef EUPHONIUM_BELL_UTILS
#define EUPHONIUM_BELL_UTILS
#include <string.h>
#include <stdint.h> // for int32_t, int64_t
#include <string.h> // for NULL
#ifdef _WIN32
#include <WinSock2.h>
#else
#include <sys/time.h>
#include <sys/time.h> // for timeval, gettimeofday
#include <unistd.h> // for usleep
#endif
#include <random>
#include <vector>
#include <cmath> // for floor
#include <string> // for string
#ifdef ESP_PLATFORM
#include "esp_system.h"
@@ -28,9 +30,9 @@ struct tv {
#if _WIN32
static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL);
SYSTEMTIME system_time;
FILETIME file_time;
uint64_t time;
SYSTEMTIME system_time;
FILETIME file_time;
uint64_t time;
GetSystemTime(&system_time);
SystemTimeToFileTime(&system_time, &file_time);
@@ -50,7 +52,9 @@ struct tv {
int32_t sec;
int32_t usec;
int64_t ms() { return (sec * (int64_t)1000) + (usec / 1000); }
int64_t ms() {
return (sec * (int64_t)1000) + (usec / 1000);
}
tv operator+(const tv& other) const {
tv result(*this);
@@ -95,7 +99,6 @@ struct tv {
#define BELL_SLEEP_MS(ms) Sleep(ms)
#define BELL_YIELD() ;
#else
#include <unistd.h>
#define BELL_SLEEP_MS(ms) usleep(ms * 1000)
#define BELL_YIELD() ;

View File

@@ -1,83 +1,76 @@
#ifndef BELL_CRYPTO_H
#define BELL_CRYPTO_H
#define Crypto CryptoMbedTLS
#include <vector>
#include <string>
#include <memory>
#include <stdexcept>
extern "C" {
#include "aes.h"
}
#include <mbedtls/base64.h>
#include <mbedtls/bignum.h>
#include <mbedtls/md.h>
#include <mbedtls/aes.h>
#include <mbedtls/pkcs5.h>
#include <mbedtls/entropy.h>
#include <mbedtls/ctr_drbg.h>
#include <string> // for string
#include <vector> // for vector
#include <mbedtls/aes.h> // for mbedtls_aes_context
#include <mbedtls/md.h> // for mbedtls_md_context_t
#include <stddef.h> // for size_t
#include <stdint.h> // for uint8_t
#define DH_KEY_SIZE 96
const static unsigned char DHPrime[] = {
/* Well-known Group 1, 768-bit prime */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9,
0x0f, 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6,
0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e,
0x08, 0x8a, 0x67, 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6,
0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e,
0x34, 0x04, 0xdd, 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a,
0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, 0xf2, 0x5f, 0x14,
0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45,
0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, 0xf4,
0x4c, 0x42, 0xe9, 0xa6, 0x3a, 0x36, 0x20, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff
};
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2,
0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1,
0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6,
0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd,
0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d,
0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45,
0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, 0xf4, 0x4c, 0x42, 0xe9,
0xa6, 0x3a, 0x36, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
static unsigned char DHGenerator[1] = {2};
class CryptoMbedTLS {
private:
mbedtls_md_context_t sha1Context;
mbedtls_aes_context aesCtx;
bool aesCtxInitialized = false;
public:
CryptoMbedTLS();
~CryptoMbedTLS();
// Base64
std::vector<uint8_t> base64Decode(const std::string& data);
std::string base64Encode(const std::vector<uint8_t>& data);
private:
mbedtls_md_context_t sha1Context;
mbedtls_aes_context aesCtx;
bool aesCtxInitialized = false;
// Sha1
void sha1Init();
void sha1Update(const std::string& s);
void sha1Update(const std::vector<uint8_t>& vec);
std::string sha1Final();
std::vector<uint8_t> sha1FinalBytes();
public:
CryptoMbedTLS();
~CryptoMbedTLS();
// Base64
std::vector<uint8_t> base64Decode(const std::string& data);
std::string base64Encode(const std::vector<uint8_t>& data);
// HMAC SHA1
std::vector<uint8_t> sha1HMAC(const std::vector<uint8_t>& inputKey, const std::vector<uint8_t>& message);
// Sha1
void sha1Init();
void sha1Update(const std::string& s);
void sha1Update(const std::vector<uint8_t>& vec);
std::string sha1Final();
std::vector<uint8_t> sha1FinalBytes();
// AES CTR
void aesCTRXcrypt(const std::vector<uint8_t>& key, std::vector<uint8_t>& iv, uint8_t* data, size_t nbytes);
// AES ECB
void aesECBdecrypt(const std::vector<uint8_t>& key, std::vector<uint8_t>& data);
// HMAC SHA1
std::vector<uint8_t> sha1HMAC(const std::vector<uint8_t>& inputKey,
const std::vector<uint8_t>& message);
// Diffie Hellman
std::vector<uint8_t> publicKey;
std::vector<uint8_t> privateKey;
void dhInit();
std::vector<uint8_t> dhCalculateShared(const std::vector<uint8_t>& remoteKey);
// AES CTR
void aesCTRXcrypt(const std::vector<uint8_t>& key, std::vector<uint8_t>& iv,
uint8_t* data, size_t nbytes);
// PBKDF2
std::vector<uint8_t> pbkdf2HmacSha1(const std::vector<uint8_t>& password, const std::vector<uint8_t>& salt, int iterations, int digestSize);
// AES ECB
void aesECBdecrypt(const std::vector<uint8_t>& key,
std::vector<uint8_t>& data);
// Random stuff
std::vector<uint8_t> generateVectorWithRandomData(size_t length);
// Diffie Hellman
std::vector<uint8_t> publicKey;
std::vector<uint8_t> privateKey;
void dhInit();
std::vector<uint8_t> dhCalculateShared(const std::vector<uint8_t>& remoteKey);
// PBKDF2
std::vector<uint8_t> pbkdf2HmacSha1(const std::vector<uint8_t>& password,
const std::vector<uint8_t>& salt,
int iterations, int digestSize);
// Random stuff
std::vector<uint8_t> generateVectorWithRandomData(size_t length);
};
#define Crypto CryptoMbedTLS
#endif

View File

@@ -1,47 +1,51 @@
#pragma once
#include <vector>
#include "pb_encode.h"
#include "pb_decode.h"
#include <string>
#include <stdint.h> // for uint8_t
#include <stdio.h> // for printf
#include <string> // for string
#include <vector> // for vector
std::vector<uint8_t> pbEncode(const pb_msgdesc_t *fields, const void *src_struct);
#include "pb.h" // for pb_msgdesc_t, pb_bytes_array_t, PB_GET_ERROR
#include "pb_decode.h" // for pb_istream_from_buffer, pb_decode, pb_istream_s
std::vector<uint8_t> pbEncode(const pb_msgdesc_t* fields,
const void* src_struct);
pb_bytes_array_t* vectorToPbArray(const std::vector<uint8_t>& vectorToPack);
void packString(char* &dst, std::string stringToPack);
void packString(char*& dst, std::string stringToPack);
std::vector<uint8_t> pbArrayToVector(pb_bytes_array_t* pbArray);
template <typename T>
T pbDecode(const pb_msgdesc_t *fields, std::vector<uint8_t> &data)
{
T pbDecode(const pb_msgdesc_t* fields, std::vector<uint8_t>& data) {
T result = {};
// Create stream
pb_istream_t stream = pb_istream_from_buffer(&data[0], data.size());
// Decode the message
if (pb_decode(&stream, fields, &result) == false) {
printf("Decode failed: %s\n", PB_GET_ERROR(&stream));
}
return result;
T result = {};
// Create stream
pb_istream_t stream = pb_istream_from_buffer(&data[0], data.size());
// Decode the message
if (pb_decode(&stream, fields, &result) == false) {
printf("Decode failed: %s\n", PB_GET_ERROR(&stream));
}
return result;
}
template <typename T>
void pbDecode(T &result, const pb_msgdesc_t *fields, std::vector<uint8_t> &data)
{
// Create stream
pb_istream_t stream = pb_istream_from_buffer(&data[0], data.size());
// Decode the message
if (pb_decode(&stream, fields, &result) == false) {
printf("Decode failed: %s\n", PB_GET_ERROR(&stream));
}
void pbDecode(T& result, const pb_msgdesc_t* fields,
std::vector<uint8_t>& data) {
// Create stream
pb_istream_t stream = pb_istream_from_buffer(&data[0], data.size());
// Decode the message
if (pb_decode(&stream, fields, &result) == false) {
printf("Decode failed: %s\n", PB_GET_ERROR(&stream));
}
}
void pbPutString(const std::string &stringToPack, char* dst);
void pbPutCharArray(const char * stringToPack, char* dst);
void pbPutBytes(const std::vector<uint8_t> &data, pb_bytes_array_t &dst);
void pbPutString(const std::string& stringToPack, char* dst);
void pbPutCharArray(const char* stringToPack, char* dst);
void pbPutBytes(const std::vector<uint8_t>& data, pb_bytes_array_t& dst);
const char* pb_encode_to_string(const pb_msgdesc_t *fields, const void *data);
const char* pb_encode_to_string(const pb_msgdesc_t* fields, const void* data);

View File

@@ -1,117 +1,101 @@
#ifndef BELL_QUEUE_H
#define BELL_QUEUE_H
#include <queue>
#include <atomic>
#include <condition_variable>
#include <atomic>
#include <queue>
namespace bell
{
template <typename dataType>
class Queue
{
private:
/// Queue
std::queue<dataType> m_queue;
/// Mutex to controll multiple access
mutable std::mutex m_mutex;
/// Conditional variable used to fire event
std::condition_variable m_cv;
/// Atomic variable used to terminate immediately wpop and wtpop functions
std::atomic<bool> m_forceExit = false;
namespace bell {
template <typename dataType>
class Queue {
private:
/// Queue
std::queue<dataType> m_queue;
/// Mutex to controll multiple access
mutable std::mutex m_mutex;
/// Conditional variable used to fire event
std::condition_variable m_cv;
/// Atomic variable used to terminate immediately wpop and wtpop functions
std::atomic<bool> m_forceExit = false;
public:
/// <summary> Add a new element in the queue. </summary>
/// <param name="data"> New element. </param>
void push(dataType const &data)
{
m_forceExit.store(false);
std::unique_lock<std::mutex> lk(m_mutex);
m_queue.push(data);
lk.unlock();
m_cv.notify_one();
}
/// <summary> Check queue empty. </summary>
/// <returns> True if the queue is empty. </returns>
bool isEmpty() const
{
std::unique_lock<std::mutex> lk(m_mutex);
return m_queue.empty();
}
/// <summary> Pop element from queue. </summary>
/// <param name="popped_value"> [in,out] Element. </param>
/// <returns> false if the queue is empty. </returns>
bool pop(dataType &popped_value)
{
std::unique_lock<std::mutex> lk(m_mutex);
if (m_queue.empty())
{
return false;
}
else
{
popped_value = m_queue.front();
m_queue.pop();
return true;
}
}
/// <summary> Wait and pop an element in the queue. </summary>
/// <param name="popped_value"> [in,out] Element. </param>
/// <returns> False for forced exit. </returns>
bool wpop(dataType &popped_value)
{
std::unique_lock<std::mutex> lk(m_mutex);
m_cv.wait(lk, [&]() -> bool
{ return !m_queue.empty() || m_forceExit.load(); });
if (m_forceExit.load())
return false;
popped_value = m_queue.front();
m_queue.pop();
return true;
}
/// <summary> Timed wait and pop an element in the queue. </summary>
/// <param name="popped_value"> [in,out] Element. </param>
/// <param name="milliseconds"> [in] Wait time. </param>
/// <returns> False for timeout or forced exit. </returns>
bool wtpop(dataType &popped_value, long milliseconds = 1000)
{
std::unique_lock<std::mutex> lk(m_mutex);
m_cv.wait_for(lk, std::chrono::milliseconds(milliseconds), [&]() -> bool
{ return !m_queue.empty() || m_forceExit.load(); });
if (m_forceExit.load())
return false;
if (m_queue.empty())
return false;
popped_value = m_queue.front();
m_queue.pop();
return true;
}
/// <summary> Queue size. </summary>
int size()
{
std::unique_lock<std::mutex> lk(m_mutex);
return static_cast<int>(m_queue.size());
}
/// <summary> Free the queue and force stop. </summary>
void clear()
{
m_forceExit.store(true);
std::unique_lock<std::mutex> lk(m_mutex);
while (!m_queue.empty())
{
//delete m_queue.front();
m_queue.pop();
}
lk.unlock();
m_cv.notify_one();
}
/// <summary> Check queue in forced exit state. </summary>
bool isExit() const
{
return m_forceExit.load();
}
};
}
public:
/// <summary> Add a new element in the queue. </summary>
/// <param name="data"> New element. </param>
void push(dataType const& data) {
m_forceExit.store(false);
std::unique_lock<std::mutex> lk(m_mutex);
m_queue.push(data);
lk.unlock();
m_cv.notify_one();
}
/// <summary> Check queue empty. </summary>
/// <returns> True if the queue is empty. </returns>
bool isEmpty() const {
std::unique_lock<std::mutex> lk(m_mutex);
return m_queue.empty();
}
/// <summary> Pop element from queue. </summary>
/// <param name="popped_value"> [in,out] Element. </param>
/// <returns> false if the queue is empty. </returns>
bool pop(dataType& popped_value) {
std::unique_lock<std::mutex> lk(m_mutex);
if (m_queue.empty()) {
return false;
} else {
popped_value = m_queue.front();
m_queue.pop();
return true;
}
}
/// <summary> Wait and pop an element in the queue. </summary>
/// <param name="popped_value"> [in,out] Element. </param>
/// <returns> False for forced exit. </returns>
bool wpop(dataType& popped_value) {
std::unique_lock<std::mutex> lk(m_mutex);
m_cv.wait(lk,
[&]() -> bool { return !m_queue.empty() || m_forceExit.load(); });
if (m_forceExit.load())
return false;
popped_value = m_queue.front();
m_queue.pop();
return true;
}
/// <summary> Timed wait and pop an element in the queue. </summary>
/// <param name="popped_value"> [in,out] Element. </param>
/// <param name="milliseconds"> [in] Wait time. </param>
/// <returns> False for timeout or forced exit. </returns>
bool wtpop(dataType& popped_value, long milliseconds = 1000) {
std::unique_lock<std::mutex> lk(m_mutex);
m_cv.wait_for(lk, std::chrono::milliseconds(milliseconds), [&]() -> bool {
return !m_queue.empty() || m_forceExit.load();
});
if (m_forceExit.load())
return false;
if (m_queue.empty())
return false;
popped_value = m_queue.front();
m_queue.pop();
return true;
}
/// <summary> Queue size. </summary>
int size() {
std::unique_lock<std::mutex> lk(m_mutex);
return static_cast<int>(m_queue.size());
}
/// <summary> Free the queue and force stop. </summary>
void clear() {
m_forceExit.store(true);
std::unique_lock<std::mutex> lk(m_mutex);
while (!m_queue.empty()) {
//delete m_queue.front();
m_queue.pop();
}
lk.unlock();
m_cv.notify_one();
}
/// <summary> Check queue in forced exit state. </summary>
bool isExit() const { return m_forceExit.load(); }
};
} // namespace bell
#endif

View File

@@ -5,4 +5,4 @@
#ifndef EUPHONIUMCLI_TIMEDEFS_H
#define EUPHONIUMCLI_TIMEDEFS_H
#endif // EUPHONIUMCLI_TIMEDEFS_H
#endif // EUPHONIUMCLI_TIMEDEFS_H

View File

@@ -1,8 +1,8 @@
#ifndef _AES_H_
#define _AES_H_
#include <stdint.h>
#include <stddef.h>
#include <stdint.h>
// #define the macros below to 1/0 to enable/disable the mode of operation.
//
@@ -12,37 +12,35 @@
// The #ifndef-guard allows it to be configured before #include'ing or at compile time.
#ifndef CBC
#define CBC 1
#define CBC 1
#endif
#ifndef ECB
#define ECB 1
#define ECB 1
#endif
#ifndef CTR
#define CTR 1
#define CTR 1
#endif
// #define AES128 1
#define AES192 1
//#define AES256 1
#define AES_BLOCKLEN 16 // Block length in bytes - AES is 128b block only
#define AES_BLOCKLEN 16 // Block length in bytes - AES is 128b block only
#if defined(AES256) && (AES256 == 1)
#define AES_KEYLEN 32
#define AES_keyExpSize 240
#define AES_KEYLEN 32
#define AES_keyExpSize 240
#elif defined(AES192) && (AES192 == 1)
#define AES_KEYLEN 24
#define AES_keyExpSize 208
#define AES_KEYLEN 24
#define AES_keyExpSize 208
#else
#define AES_KEYLEN 16 // Key length in bytes
#define AES_keyExpSize 176
#define AES_KEYLEN 16 // Key length in bytes
#define AES_keyExpSize 176
#endif
struct AES_ctx
{
struct AES_ctx {
uint8_t RoundKey[AES_keyExpSize];
#if (defined(CBC) && (CBC == 1)) || (defined(CTR) && (CTR == 1))
uint8_t Iv[AES_BLOCKLEN];
@@ -51,41 +49,39 @@ struct AES_ctx
void AES_init_ctx(struct AES_ctx* ctx, const uint8_t* key);
#if (defined(CBC) && (CBC == 1)) || (defined(CTR) && (CTR == 1))
void AES_init_ctx_iv(struct AES_ctx* ctx, const uint8_t* key, const uint8_t* iv);
void AES_init_ctx_iv(struct AES_ctx* ctx, const uint8_t* key,
const uint8_t* iv);
void AES_ctx_set_iv(struct AES_ctx* ctx, const uint8_t* iv);
#endif
#if defined(ECB) && (ECB == 1)
// buffer size is exactly AES_BLOCKLEN bytes;
// you need only AES_init_ctx as IV is not used in ECB
// buffer size is exactly AES_BLOCKLEN bytes;
// you need only AES_init_ctx as IV is not used in ECB
// NB: ECB is considered insecure for most uses
void AES_ECB_encrypt(const struct AES_ctx* ctx, uint8_t* buf);
void AES_ECB_decrypt(const struct AES_ctx* ctx, uint8_t* buf);
#endif // #if defined(ECB) && (ECB == !)
#endif // #if defined(ECB) && (ECB == !)
#if defined(CBC) && (CBC == 1)
// buffer size MUST be mutile of AES_BLOCKLEN;
// Suggest https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS7 for padding scheme
// NOTES: you need to set IV in ctx via AES_init_ctx_iv() or AES_ctx_set_iv()
// no IV should ever be reused with the same key
// no IV should ever be reused with the same key
void AES_CBC_encrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, size_t length);
void AES_CBC_decrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, size_t length);
#endif // #if defined(CBC) && (CBC == 1)
#endif // #if defined(CBC) && (CBC == 1)
#if defined(CTR) && (CTR == 1)
// Same function for encrypting as for decrypting.
// Same function for encrypting as for decrypting.
// IV is incremented for every block, and used after encryption as XOR-compliment for output
// Suggesting https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS7 for padding scheme
// NOTES: you need to set IV in ctx with AES_init_ctx_iv() or AES_ctx_set_iv()
// no IV should ever be reused with the same key
// no IV should ever be reused with the same key
void AES_CTR_xcrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, size_t length);
#endif // #if defined(CTR) && (CTR == 1)
#endif // #if defined(CTR) && (CTR == 1)
#endif // _AES_H_
#endif // _AES_H_