Skip to content

Instantly share code, notes, and snippets.

@hexatridecimal
Forked from benders/rsa-test.rb
Created April 12, 2012 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hexatridecimal/2367966 to your computer and use it in GitHub Desktop.
Save hexatridecimal/2367966 to your computer and use it in GitHub Desktop.
Ruby RSA using OpenSSL example
require 'openssl'
require 'base64'
require 'stringio'
plaintext = StringIO.new <<-EOF
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Also, because I said so.
EOF
target_key = OpenSSL::PKey::RSA.new(640)
# target_key.e = OpenSSL::BN.new('65537') # Note it's a String
# target_key.n = OpenSSL::BN.new(modulus)
block_size = target_key.n.num_bytes
min_padding = 11
puts "#{plaintext.length} byte plaintext, #{target_key.n.to_i.size} byte modulus"
# puts "n=" + target_key.n.to_s
puts
raise "Incorrect exponent" unless target_key.e == 65537
output = ""
while input = plaintext.read(block_size - min_padding) do
puts "(Encrypting #{input.length.to_s} bytes)"
output +=
target_key.public_encrypt(input, OpenSSL::PKey::RSA::PKCS1_PADDING)
end
encoded = [output].pack("m").gsub(/\n/,'')
puts encoded + " (#{encoded.length})"
puts
ciphertext = StringIO.new( Base64.decode64( encoded ) )
output = ""
while input = ciphertext.read(block_size) do
puts "(Decrypting #{input.length.to_s} bytes)"
output +=
target_key.private_decrypt(input, OpenSSL::PKey::RSA::PKCS1_PADDING)
end
puts output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment