Skip to content

Instantly share code, notes, and snippets.

@marcosgz
Forked from gevans/encryption-decryption.rb
Created June 19, 2021 14:13
Show Gist options
  • Save marcosgz/687382e6d2e8072747a7849c5413384a to your computer and use it in GitHub Desktop.
Save marcosgz/687382e6d2e8072747a7849c5413384a to your computer and use it in GitHub Desktop.
A couple examples of using asymmetric RSA signing and encryption using Ruby's OpenSSL libraries.
require 'openssl'
key = OpenSSL::PKey::RSA.new(2048)
p encrypted_string = key.public_encrypt('my plaintext string', OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING)
p decrypted_string = key.private_decrypt(encrypted_string, OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING)
require 'openssl'
key = OpenSSL::PKey::RSA.new(2048)
data = 'my string to sign'
p signature = key.sign(OpenSSL::Digest::SHA256.new, data)
pubkey = key.public_key
if pubkey.verify(OpenSSL::Digest::SHA256.new, signature, data)
puts 'the signature is valid'
else
puts 'the signature is invalid'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment