Created
June 23, 2021 22:16
-
-
Save marcosgz/444b723fe08a8f6894c7df5bb4884e1b to your computer and use it in GitHub Desktop.
RSA crypt/decrypt example using ruby and openssl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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