Skip to content

Instantly share code, notes, and snippets.

@marcosgz
Created June 23, 2021 22:16
Show Gist options
  • Save marcosgz/444b723fe08a8f6894c7df5bb4884e1b to your computer and use it in GitHub Desktop.
Save marcosgz/444b723fe08a8f6894c7df5bb4884e1b to your computer and use it in GitHub Desktop.
RSA crypt/decrypt example using ruby and openssl
# Generate keys
# $ openssl genrsa -des3 -out private.pem 2048
# $ openssl rsa -in private.pem -outform PEM -pubout -out public.pem
# $ irb
require 'openssl'
require 'base64'
# Encrypt
public_key = OpenSSL::PKey::RSA.new(File.read('public.pem'))
encrypted_string = Base64.encode64(public_key.public_encrypt('Hello World!'))
puts(encrypted_string)
# Decrypt
password = 'teste'
private_key = OpenSSL::PKey::RSA.new(File.read('private.pem'),password)
decrypted_string = private_key.private_decrypt(Base64.decode64(encrypted_string))
puts(decrypted_string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment