Criptografía en C++: guía completa de cifrado y hashing

Entrenador de Python en Línea para Principiantes

Aprende Python fácilmente sin sobrecargarte de teoría. Resuelve tareas prácticas con verificación automática, recibe pistas y escribe código directamente en el navegador, sin instalar nada.

Start Course

Criptografía en C++: de la teoría a la práctica del cifrado y hashing



La criptografía es la base fundamental de la seguridad de las aplicaciones modernas. En C++, el desarrollador tiene a su disposición potentes bibliotecas que permiten implementar tanto el cifrado simétrico/asimétrico como el hashing criptográfico. En este material analizaremos dos bibliotecas clave: OpenSSL (el estándar de facto) y Crypto++ (C++ puro, fácil de integrar). Aprenderá cómo cifrar datos, verificar la integridad y proteger contraseñas.



Conceptos criptográficos fundamentales

Antes de pasar al código, es importante comprender tres operaciones básicas:

  • Cifrado simétrico (AES, ChaCha20): una sola clave para cifrar y descifrar. Rápido, adecuado para grandes volúmenes de datos.
  • Cifrado asimétrico (RSA, ECC): un par de claves (pública/privada). Se utiliza para el intercambio de claves y firmas digitales.
  • Hashing (SHA-256, MD5): transformación irreversible de datos en una cadena de longitud fija. Se utiliza para verificar la integridad y almacenar contraseñas.


1. Trabajar con OpenSSL en C++

OpenSSL es una biblioteca multiplataforma en C, accesible mediante enlace. Instalación: sudo apt install libssl-dev (Linux) o mediante vcpkg/conan para Windows.



Ejemplo: cifrado simétrico AES-256-CBC

#include <iostream>#include <string>#include <openssl/evp.h>#include <openssl/rand.h>

std::string aes_encrypt(const std::string& plaintext, const unsigned char* key, const unsigned char* iv) { EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, key, iv);

std::string ciphertext(plaintext.size() + 16, '\\0'); int len = 0, ciphertext_len = 0; EVP_EncryptUpdate(ctx, reinterpret_cast<unsigned char*>(&ciphertext[0]), &len, reinterpret_cast<const unsigned char*>(plaintext.data()), plaintext.size()); ciphertext_len = len; EVP_EncryptFinal_ex(ctx, reinterpret_cast<unsigned char*>(&ciphertext[ciphertext_len]), &len); ciphertext_len += len; ciphertext.resize(ciphertext_len); EVP_CIPHER_CTX_free(ctx); return ciphertext;}

int main() { unsigned char key[32], iv[16]; RAND_bytes(key, sizeof(key)); // Generación de clave aleatoria RAND_bytes(iv, sizeof(iv));

std::string data = "Mensaje secreto"; std::string encrypted = aes_encrypt(data, key, iv); std::cout << "Cifrado: " << encrypted.size() << " bytes" << std::endl; return 0;}


Hashing SHA-256 con OpenSSL

#include <iostream>#include <openssl/sha.h>

std::string sha256(const std::string& str) { unsigned char hash[SHA256_DIGEST_LENGTH]; SHA256_CTX sha256; SHA256_Init(&sha256); SHA256_Update(&sha256, str.c_str(), str.size()); SHA256_Final(hash, &sha256);

std::string output; for(int i = 0; i < SHA256_DIGEST_LENGTH; i++) { char buf[3]; sprintf(buf, "%02x", hash[i]); output += buf; } return output;}

int main() { std::cout << "SHA-256: " << sha256("¡Hola, Crypto!") << std::endl; return 0;}


2. Biblioteca Crypto++ (implementación pura en C++)

Crypto++ (cryptopp) es una biblioteca completa en C++ sin dependencias externas. Instalación: sudo apt install libcrypto++-dev o descargar desde cryptopp.com.



Ejemplo: cifrado RSA con Crypto++

#include <iostream>#include <string>#include <cryptopp/rsa.h>#include <cryptopp/osrng.h>#include <cryptopp/base64.h>

int main() { using namespace CryptoPP;

AutoSeededRandomPool rng; Inve

Recommendations