Created
May 13, 2009 21:44
-
-
Save benders/111332 to your computer and use it in GitHub Desktop.
Ruby RSA using OpenSSL example
This file contains hidden or 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
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