基于OpenSSL实现AES/CFB8持续加密的C++技术求助
关于Minecraft服务器复刻项目中AES/CFB8持续加密的问题
我最近在做一个用C++复刻Minecraft服务器的副业项目,现在卡在了加密环节。按照Minecraft协议要求,需要用**支持持续更新(无需每个数据包结束后重启)**的AES/CFB8加密算法。网上找的方案要么无法正常运行,要么是命令行实现,求帮忙。
Cipher.h
class Cipher { public: enum CipherType { ENCRYPT, DECRYPT }; private: EVP_CIPHER_CTX* ctx; CipherType type; bool hasFinished; public: Cipher(const char* key, const char* iv, CipherType type); ~Cipher(); int update(char* in, int inl, char* out); int final(char* out); int getMinimumBufLength(int size); };
Cipher.cpp
Cipher::Cipher(const char* key, const char* iv, CipherType type) : type(type), hasFinished(false) { ctx = EVP_CIPHER_CTX_new(); EVP_CIPHER_CTX_init(ctx); if(type == CipherType::ENCRYPT) EVP_EncryptInit_ex(ctx, EVP_aes_256_cfb8(), nullptr, (unsigned char*)key, (unsigned char*)iv); else EVP_DecryptInit_ex(ctx, EVP_aes_256_cfb8(), nullptr, (unsigned char*)key, (unsigned char*)iv); } Cipher::~Cipher() { EVP_CIPHER_CTX_free(ctx); } int Cipher::getMinimumBufLength(int size) { return type == CipherType::DECRYPT ? size : size + AES_BLOCK_SIZE * 2; } int Cipher::update(char* in, int inl, char* out) { int len; EVP_CipherUpdate(ctx, (unsigned char*)out, &len, (unsigned char*)in, inl); return len; } int Cipher::final(char* out) { int len; EVP_EncryptFinal_ex(ctx, (unsigned char*)out, &len); return len; }
Cipher-test.cpp
TEST_CASE("Cipher AES/CFB8") { char* key = "AAAAAAAAAZEFRGUINJFKDFIVJ"; char* iv = "AUJVFEUB"; Cipher encryptionCipher(key, iv, Cipher::CipherType::ENCRYPT); Cipher decryptionCipher(key, iv, Cipher::CipherType::DECRYPT); std::string data = "Hello World ! This is some soon to be encrypted string !"; char encData[encryptionCipher.getMinimumBufLength(data.size() + 1)]; int outLen = encryptionCipher.update(data.data(), data.size() + 1, encData); int fLen = encryptionCipher.final(encData + outLen); CHECK(data != std::string(encData)); char decData[decryptionCipher.getMinimumBufLength(outLen + fLen)]; outLen = decryptionCipher.update(encData, outLen + fLen, decData); decryptionCipher.final(decData + outLen); CHECK(data == std::string(decData)); }
提前感谢!
编辑:我想知道是否需要补充代码来实现加密的“持续”特性。
内容的提问来源于stack exchange,提问作者Lygaen
相关产品推荐
相关产品推荐

