This code defines two main classes: Base64
and RSA_Sample
. The Base64
class provides methods for encoding and decoding data in Base64 format, while the RSA_Sample
class handles RSA key generation, encryption, and decryption of messages.
- Methods:
base64_encode
: Takes a byte array and its length as input, encodes it to a Base64 string without newlines, and returns the encoded string.base64_decode
: Accepts a Base64 encoded string, decodes it back to its original byte form, and returns the decoded string.
- Methods:
generateRSAKeys
: Generates a pair of RSA keys (public and private) with a key size of 4096 bits. The public key is extracted from the private key and stored in memory.encryptMessage
: Encrypts a given plaintext message using the public key and returns the encrypted message encoded in Base64 format.decryptMessage
: Takes a Base64 encoded encrypted message, decodes it, and decrypts it using the private key, returning the original plaintext message.
In the main
function:
- RSA keys are generated.
- An original message ("Hello, RSA Encryption!") is defined and displayed.
- The message is encrypted using the public key, and the encrypted message is displayed in Base64 format.
- The encrypted message is decrypted using the private key, and the decrypted message is displayed.
- Finally, the allocated RSA keys are freed to prevent memory leaks.
- tl;dr Keep in mind that base64 encoding make key bigger than it's actuall size is. Decode it before usage (if you are encoding it)
To compile and run this code on a Linux system, follow these steps:
-
Install OpenSSL Development Libraries: Make sure you have the OpenSSL library installed. You can install it using your package manager. For example, on Ubuntu, you can run:
sudo apt-get update sudo apt-get install libssl-dev
-
Create a Source File: Save the provided code in a file named
rsa_example.cpp
. -
Compile the Code: Use the
g++
compiler to compile the code, linking it with the OpenSSL libraries. Run the following command in your terminal:g++ -O2 rsa_example.cpp -o rsa_example -lssl -lcrypto
-
Run the Executable: After successful compilation, run the program with:
./rsa_example
This code serves as a basic demonstration of RSA encryption and decryption, showcasing how to securely encode messages using public key cryptography. It can be extended or integrated into larger applications (but I don't recommend) requiring secure data transmission.