nunojob:~ dscape/08$ echo The Black Sheep

Well I finished the encrypt with RSA on ruby some hours ago and felt like sharing :)

Case you feel like doing something back for me just download the latest release of my beta twitter client and send me some comments to my email. It’s pretty hard to test something when my environment is completely contaminated !

require 'openssl'
require 'Base64'

class Rudolph
  class Crypt
    def initialize data_path
      @data_path = data_path
      @private   = get_key 'id_rsa'
      @public    = get_key ''

    def encrypt_string message

    def decrypt_string message
      @private.private_decrypt Base64::decode64(message)

    def self.generate_keys data_path
      rsa_path = File.join(data_path, 'rsa')
      privkey  = File.join(rsa_path, 'id_rsa')
      pubkey   = File.join(rsa_path, '')
      unless File.exists?(privkey) || File.exists?(pubkey)
        keypair  = OpenSSL::PKey::RSA.generate(1024)
        Dir.mkdir(rsa_path) unless File.exist?(rsa_path), 'w') { |f| f.write keypair.to_pem } unless File.exists? privkey, 'w') { |f| f.write keypair.public_key.to_pem } unless File.exists? pubkey

    def get_key filename, 'rsa', filename))

Comments on: "RSA Encrypt & Decrypt in ruby" (7)

  1. […] RSA Encrypt (tags: ruby rsa encrypt decrypt) […]

  2. does your shoes client already supports Shoes 2? :-) it’s awesome! :D

  3. Yup Shoes 2 and ruby 1.9

  4. Hey this is really good – i was looking for something like this..

    Since i am a beginner @ programming (hence take the comments with a grain of salt) i tried to use your code and ran into the following issues:
    – when i ran in my main.rb application it gave me an error as the pub/priv key were not present which was due to the get_key function (before the keys were generated).

    – because i am working on Windows – i needed to append two slashes for the directory paths

    in order to generate keys using the example above – i had to comment out the initialize statements…so my initial code was

    @enc =“C:\\temp\\”)

    then the above lines were not longer required and i could uncomment the initialize statement and get on with using your code for its function.. which by the way worked perfectly… so thank you.

  5. Hi Andrew,

    This only works in Linux.

    To use it in windows you can install cygwin and deploy openssl.

    This is not very beginner suited material but I’m sure you’ll do fine

  6. Alexey Trofimenko said:

    thanks. saved couple of minutes for me

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: