A implementação do AES (Advanced Encryption Standard) em C++ pode ser feita usando bibliotecas criptográficas, como OpenSSL, Crypto++, ou implementando o algoritmo manualmente. Neste exemplo, vou mostrar como usar a biblioteca Crypto++ para criptografar e descriptografar usando AES em modo de bloco CBC (Cipher Block Chaining). Certifique-se de ter a biblioteca Crypto++ instalada no seu sistema.
Certifique-se de incluir a biblioteca Crypto++ no seu projeto e de compilar o código com as flags apropriadas para vincular a biblioteca. Este é apenas um exemplo básico. Certifique-se de considerar a segurança da chave e do IV em um ambiente de produção e de seguir as melhores práticas de segurança ao lidar com criptografia.#include
#include #include #include #include #include #include using namespace CryptoPP; std::string AES_Encrypt(const std::string& plaintext, const std::string& key, const std::string& iv) { std::string ciphertext; try { CBC_Mode ::Encryption encryption((byte*)key.c_str(), key.length(), (byte*)iv.c_str()); StringSource(plaintext, true, new StreamTransformationFilter(encryption, new StringSink(ciphertext) ) ); } catch (const Exception& e) { std::cerr << e.what() << std::endl; std::exit(1); } return ciphertext; } std::string AES_Decrypt(const std::string& ciphertext, const std::string& key, const std::string& iv) { std::string decryptedtext; try { CBC_Mode ::Decryption decryption((byte*)key.c_str(), key.length(), (byte*)iv.c_str()); StringSource(ciphertext, true, new StreamTransformationFilter(decryption, new StringSink(decryptedtext) ) ); } catch (const Exception& e) { std::cerr << e.what() << std::endl; std::exit(1); } return decryptedtext; } int main() { // Chave de 16 bytes (128 bits) e IV de 16 bytes para AES-128 std::string key = "0123456789abcdef"; std::string iv = "0123456789abcdef"; std::string plaintext = "Hello, AES!"; std::cout << "Texto original: " << plaintext << std::endl; // Criptografar std::string ciphertext = AES_Encrypt(plaintext, key, iv); std::cout << "Texto criptografado: "; for (char c : ciphertext) std::cout << std::hex << std::setw(2) << std::setfill('0') << (int)(unsigned char)c; std::cout << std::endl; // Descriptografar std::string decryptedtext = AES_Decrypt(ciphertext, key, iv); std::cout << "Texto descriptografado: " << decryptedtext << std::endl; return 0; }
Comentários
Postar um comentário