Implementing RSA Encryption in Ruby using OpenSSL

To implement this algorithm in Ruby using OpenSSL, we can follow these steps:

1. Generate the public and private keys by creating a new instance of `OpenSSL::PKey` with the appropriate options. The `generate_key` method is used to generate a key pair consisting of a public and private key.

2. Encrypt data using the public key (in this case, “Hello, world!”) by converting it into an array of bytes, then encrypting each byte individually using the `cipher` method. This results in a ciphertext that can be sent securely over an unsecured channel to the recipient.

3. Decrypt data using the private key by first decoding the ciphertext back into its original form as bytes, then decrypting each byte individually using the `decipher` method. This results in the plaintext message that was originally sent.

Here’s an example implementation of RSA encryption and decryption in Ruby:

require 'openssl'

# Generate a new key pair with 2048-bit keys
key = OpenSSL::PKey::RSA.new(2048) # Creates a new RSA key object with a key length of 2048 bits
key.generate_key # Generates a new public and private key pair

# Get the public and private keys as strings in PEM format
public_key = key.public_key.to_pem # Retrieves the public key as a string in PEM format
private_key = key.private_key.to_pem # Retrieves the private key as a string in PEM format

# Encrypt a message using the public key (in this case, "Hello, world!")
message = "Hello, world!"
ciphertext = OpenSSL::Cipher.new('RSA').encrypt(OpenSSL::Digest.hexdigest(message)) # Creates a new cipher object using the RSA algorithm and encrypts the message using the public key

# Decrypt the ciphertext using the private key
decrypted_message = OpenSSL::Cipher.new('RSA').decrypt(ciphertext, key) # Creates a new cipher object using the RSA algorithm and decrypts the ciphertext using the private key
puts decrypted_message # Prints the decrypted message to the console

In this example, we first generate a new RSA key pair with 2048-bit keys using `OpenSSL::PKey`. We then convert the public and private keys to PEM format for storage or transmission. To encrypt a message, we use the `encrypt` method of the OpenSSL cipher object, which takes as input the hexadecimal digest of the plaintext message (in this case, “Hello, world!”). The resulting ciphertext is then decrypted using the private key and printed to the console.

Note that in practice, it’s generally recommended to use a more secure encryption algorithm than RSA for sensitive data due to its vulnerability to certain attacks such as padding oracle attacks. However, RSA remains an important tool for public-key cryptography and is widely used in many applications today.

SICORPS