Friday, May 12, 2023

How to use OpenSSL to encrypt and decrypt data in C++



This example generates a random key and initialization vector, encrypts a message using AES-256-CBC, and then decrypts the message using the same key and initialization vector.

Note that this example uses a hardcoded plaintext message, but you can replace this with any message you want to encrypt.

Also, remember to include the necessary OpenSSL headers and links against the OpenSSL library when compiling your code.

#include <openssl/aes.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>

void encrypt_decrypt_example() {
// Generate a random key
unsigned char key[AES_BLOCK_SIZE];
RAND_bytes(key, AES_BLOCK_SIZE);

// Generate a random initialization vector
unsigned char iv[AES_BLOCK_SIZE];
RAND_bytes(iv, AES_BLOCK_SIZE);

// Plaintext message to be encrypted
unsigned char plaintext[] = "This is a secret message.";

// Encrypt the message using AES-256-CBC
AES_KEY aes_key;
AES_set_encrypt_key(key, 256, &aes_key);


int len = strlen((char*)plaintext);
int padding = AES_BLOCK_SIZE - len % AES_BLOCK_SIZE;
int ciphertext_len = len + padding;

unsigned char* ciphertext = new unsigned char[ciphertext_len];

AES_cbc_encrypt(plaintext, ciphertext, ciphertext_len, &aes_key, iv, AES_ENCRYPT);

// Decrypt the message
AES_set_decrypt_key(key, 256, &aes_key);
unsigned char* decrypted = new unsigned char[ciphertext_len];
AES_cbc_encrypt(ciphertext, decrypted, ciphertext_len, &aes_key, iv, AES_DECRYPT);


// Print the original message and decrypted message
printf("Original message: %s\n", plaintext);
printf("Decrypted message: %s\n", decrypted);


delete[] ciphertext;
delete[] decrypted;

}


OpenSSL has had some security vulnerabilities in the past, but it is generally considered a secure and reliable encryption library. Like any software, it is possible for hackers to find new vulnerabilities or exploit existing ones. However, OpenSSL is also a widely used and actively maintained open-source project, so security vulnerabilities are typically discovered and fixed quickly.

It's important to keep your OpenSSL installation up to date with the latest security patches, and to follow best practices for securing your system and network. Additionally, it's a good idea to use strong passwords and encryption keys, and to be cautious when sharing sensitive information over the internet. While no system is 100% secure, taking these steps can help minimize the risk of hacking and data breaches.

No comments:

Post a Comment

LeetCode C++ Cheat Sheet June

🎯 Core Patterns & Representative Questions 1. Arrays & Hashing Two Sum – hash map → O(n) Contains Duplicate , Product of A...