with_rsa.rb

Heads up: This description was created by AI and might not be 100% accurate.

This Ruby code snippet demonstrates RSA encryption and decryption using the openssl library. It generates a 2048-bit RSA key pair (private and public keys). A string “Ruby” is encrypted using the public key and then successfully decrypted using the corresponding private key, showcasing the basic functionality of asymmetric encryption.

Ruby code snippet

require 'openssl'
#=> true

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

secret = 'Ruby'
#=> "Ruby"

enc_data = rsa_public.public_encrypt(secret)
#=> 
"F\xCB\xD6\xBA#\xE1\x8B\xE1\x04\xCC\x83\xAAj\xB3\xB7\xE1\xF1\xCC`\a\xDCa\x91O\xF...

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

Executed with Ruby 3.4.8.