8) Using RSA algorightm Encrypt the text and Decrypt the Same.
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void handle_errors(const char *msg) {
fprintf(stderr, "%s\n", msg);
ERR_print_errors_fp(stderr);
exit(1);
}
RSA* generate_rsa_keypair(int bits) {
RSA *rsa = RSA_new();
BIGNUM *bn = BN_new();
if (!BN_set_word(bn, RSA_F4)) handle_errors("Error setting BIGNUM word.");
if (!RSA_generate_key_ex(rsa, bits, bn, NULL)) handle_errors("Error generating RSA key
pair.");
BN_free(bn);
return rsa;
}
int main() {
// Step 1: Generate RSA Key Pair
int bits = 2048;
RSA *rsa = generate_rsa_keypair(bits);
// Step 2: Prepare the message to encrypt
const char *message = "Hello, RSA encryption!";
unsigned char encrypted[256]; // Buffer for encrypted message
unsigned char decrypted[256]; // Buffer for decrypted message
int encrypted_length, decrypted_length;
printf("Original message: %s\n", message);
// Step 3: Encrypt the message using the public key
encrypted_length = RSA_public_encrypt(strlen(message), (unsigned char *)message,
encrypted, rsa, RSA_PKCS1_OAEP_PADDING);
if (encrypted_length == -1) handle_errors("Error encrypting message.");
printf("Encrypted message (hex): ");
for (int i = 0; i < encrypted_length; i++) {
printf("%02x", encrypted[i]);
}
printf("\n");
// Step 4: Decrypt the message using the private key
decrypted_length = RSA_private_decrypt(encrypted_length, encrypted, decrypted, rsa,
RSA_PKCS1_OAEP_PADDING);
if (decrypted_length == -1) handle_errors("Error decrypting message.");
decrypted[decrypted_length] = '\0'; // Null-terminate the decrypted message
printf("Decrypted message: %s\n", decrypted);
// Clean up
RSA_free(rsa);
return 0;
}
OUTPUT
LIBRARIES:
sudo apt update
sudo apt install libssl-dev