Ruby Quick Reference

Quick reference for efficient coding

View the Project on GitHub YumaYX/RubyQuickReference

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:0x00007f820da44098 oid=rsaEncryption>
rsa_public = rsa_private.public_key
#=> #<OpenSSL::PKey::RSA:0x00007f820db3f9c0 oid=rsaEncryption>

secret = 'Ruby'
#=> "Ruby"

enc_data = rsa_public.public_encrypt(secret)
#=> "\xA5\xBDH\x9F\x88:\xA2\xC2$\rEN\x93\x00M32K\\\x17\x87\x9D;k\x01\xA9\xE6...

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

Executed with Ruby 3.3.5