Files
bishe-STM32/QT/src/CryptoUtils.cpp
T
2026-05-01 20:29:02 +08:00

49 lines
1.4 KiB
C++

#include "CryptoUtils.h"
#include "crypto/tiny_aes.hpp"
namespace {
QByteArray removePkcs7Padding(const QByteArray &data)
{
if (data.isEmpty()) {
return {};
}
const int padding = static_cast<unsigned char>(data.back());
if (padding < 1 || padding > AES_BLOCKLEN || padding > data.size()) {
return data;
}
for (int i = data.size() - padding; i < data.size(); ++i) {
if (static_cast<unsigned char>(data.at(i)) != padding) {
return data;
}
}
return data.left(data.size() - padding);
}
}
QByteArray CryptoUtils::decryptAes128CbcBase64(const QByteArray &encryptedBase64)
{
static const uint8_t key[AES_KEYLEN] = {
0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6,
0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c
};
static const uint8_t iv[AES_BLOCKLEN] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
};
const QByteArray encrypted = QByteArray::fromBase64(encryptedBase64);
if (encrypted.isEmpty() || (encrypted.size() % AES_BLOCKLEN) != 0) {
return {};
}
QByteArray buffer = encrypted;
AES_ctx ctx;
AES_init_ctx_iv(&ctx, key, iv);
AES_CBC_decrypt_buffer(&ctx, reinterpret_cast<uint8_t*>(buffer.data()), static_cast<size_t>(buffer.size()));
return removePkcs7Padding(buffer);
}