Skip to the content.

with_rsa.rb(encryption)

  1. Generate RSA Key Pair:
    • Import OpenSSL library.
    • Generate a 2048-bit RSA private key.
    • Derive the corresponding public key.
  2. Encrypt Data with RSA:
    • Use the RSA public key to encrypt the string ‘Ruby’.
    • Produce encrypted data (enc_data).
  3. Decrypt Data with RSA:
    • Employ the RSA private key to decrypt the previously encrypted data (enc_data).
    • Retrieve the original string (‘Ruby’).

These snippets showcase RSA key generation, encryption, and decryption using the OpenSSL library in Ruby.

Execution:

require 'openssl'
#=> true

rsa_private = OpenSSL::PKey::RSA.generate(2048)
#=> #<OpenSSL::PKey::RSA:0x00007fa0c06c00a8 oid=rsaEncryption>
rsa_public = rsa_private.public_key
#=> #<OpenSSL::PKey::RSA:0x00007fa0c06d2a50 oid=rsaEncryption>

secret = 'Ruby'
#=> "Ruby"

enc_data = rsa_public.public_encrypt(secret)
#=> "v+\x82V\"&,\xB6\xA4l\xF3\x9C(\xE5ShD\xFE\x80T\x1A\x99(\xACduV\xD3\x13\x...

rsa_private.private_decrypt(enc_data)
#=> "Ruby"

Executed with Ruby 3.3.6