Ruby encrypt and decrypt using RSA
Examples of how to encrypt and decrypt strings using RSA in ruby
require 'opensssl'
my_string = 'dharshan bharathuru'
# specify key size as args
key1 = OpenSSL::PKey::RSA.new 2048
# specify with a secret file
key2 = OpenSSL::PKey::RSA.new(File.read('secret.pem'))
# secret key can be formed with RSAKeyPair of XML string
# you can check the specified key size as bellow
key_length = key2.n.num_bytes * 8
# or from terminal use bellow
openssl rsa -in secret.pem -noout -text
encrypted_string = key1.public_encrypt(my_string)
# "*\x0E\xB6\x8B5*\xB8\xFF\xB2\xE6\xC6\xA5\xFA\xF4L"
# you can encode it with base64
require 'base64'
encoded_string = Base64.encode64(encrypted_string)
# Decode using base64
decoded_string = Base64.decode64(encoded_string)
# Decrypt using private key
decrypted_string = key1.private_decrypt(decoded_string)
# dharshan_bharathuru
http://ruby-doc.org/stdlib-2.5.1/libdoc/openssl/rdoc/OpenSSL/PKey/RSA.html https://superdry.apphb.com/tools/online-rsa-key-converter https://en.wikipedia.org/wiki/RSA_(cryptosystem)
PreviousHow to Reduce Memory Usage for Rails and Sidekiq?NextRuby most used Array#methods and differences
Last updated