2024-12-20 02:03:16 +00:00
|
|
|
#pragma once
|
|
|
|
|
2024-12-21 04:23:44 +00:00
|
|
|
#include <cstddef>
|
2024-12-20 02:03:16 +00:00
|
|
|
#include <cstdint>
|
|
|
|
|
2024-12-20 21:02:40 +00:00
|
|
|
#if USE_WIN_CRYPTO
|
|
|
|
#include <windows.h>
|
|
|
|
|
|
|
|
#include <bcrypt.h>
|
2024-12-21 16:35:15 +00:00
|
|
|
#elif USE_OPENSSL
|
|
|
|
#include <openssl/evp.h>
|
2024-12-20 21:02:40 +00:00
|
|
|
#endif
|
|
|
|
|
2024-12-20 02:03:16 +00:00
|
|
|
namespace AES {
|
|
|
|
|
|
|
|
constexpr size_t kKeyLen = 16; // Key length in bytes
|
|
|
|
constexpr size_t kKeyExpansionSize = 176;
|
|
|
|
constexpr size_t kBlockLen = 16; // Block length in bytes - AES is 128b block only
|
|
|
|
|
|
|
|
struct AES_ctx {
|
2024-12-20 21:02:40 +00:00
|
|
|
#if USE_WIN_CRYPTO
|
|
|
|
BCRYPT_ALG_HANDLE hAlg;
|
|
|
|
BCRYPT_KEY_HANDLE hKey;
|
|
|
|
uint8_t iv[0x10];
|
2024-12-21 16:35:15 +00:00
|
|
|
#elif USE_OPENSSL
|
|
|
|
EVP_CIPHER_CTX* cipher_ctx;
|
2024-12-20 21:02:40 +00:00
|
|
|
#else
|
2024-12-20 02:03:16 +00:00
|
|
|
uint8_t RoundKey[kKeyExpansionSize];
|
|
|
|
uint8_t Iv[16];
|
2024-12-20 21:02:40 +00:00
|
|
|
#endif
|
2024-12-20 02:03:16 +00:00
|
|
|
};
|
|
|
|
|
2024-12-21 04:23:44 +00:00
|
|
|
bool AES_init_ctx_iv(AES_ctx* ctx, const uint8_t* key, const uint8_t* iv);
|
2024-12-20 02:03:16 +00:00
|
|
|
|
|
|
|
// 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
|
2024-12-20 21:02:40 +00:00
|
|
|
size_t AES_CBC_encrypt_buffer(AES_ctx* ctx, uint8_t* buf, size_t length);
|
|
|
|
size_t AES_CBC_decrypt_buffer(AES_ctx* ctx, uint8_t* buf, size_t length);
|
|
|
|
|
2024-12-21 16:35:15 +00:00
|
|
|
#if USE_WIN_CRYPTO || USE_OPENSSL
|
2024-12-20 21:02:40 +00:00
|
|
|
bool AES_cleanup(AES_ctx* ctx);
|
|
|
|
#else
|
2024-12-21 04:23:44 +00:00
|
|
|
inline bool AES_cleanup(AES_ctx* ctx) {
|
|
|
|
return true;
|
|
|
|
}
|
2024-12-20 21:02:40 +00:00
|
|
|
#endif
|
2024-12-20 02:03:16 +00:00
|
|
|
|
|
|
|
} // namespace AES
|