Created
January 17, 2012 11:16
-
-
Save qertoip/1626282 to your computer and use it in GitHub Desktop.
RSA - creating key pair, encrypting and decrypting helpers
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
# -*- encoding : utf-8 -*- | |
require 'openssl' | |
module RSA | |
def self.create_keys( priv = "rsa_key", pub = "#{priv}.pub", bits = 1024 ) | |
private_key = OpenSSL::PKey::RSA.new( bits ) | |
File.open( priv, "wb+" ) { |fp| fp << private_key.to_s } | |
File.open( pub, "wb+" ) { |fp| fp << private_key.public_key.to_s } | |
private_key | |
end | |
def self.create_keys_in_memory( bits = 1024 ) | |
private_key = OpenSSL::PKey::RSA.new( bits ) | |
[private_key.public_key.to_s, private_key.to_s] | |
end | |
def self.encrypt( text, key ) | |
RSA::Key.new( key ).encrypt( text ) | |
end | |
def self.decrypt( text, key ) | |
RSA::Key.new( key ).decrypt( text ) | |
end | |
class Key | |
def initialize( data ) | |
@public = ( data =~ /^-----BEGIN (RSA|DSA) PRIVATE KEY-----$/ ).nil? | |
@key = OpenSSL::PKey::RSA.new( data ) | |
end | |
def self.from_file( filename ) | |
self.new( File.read( filename ) ) | |
end | |
def encrypt( text ) | |
Base64.encode64( @key.send("#{key_type}_encrypt", text ) ) | |
end | |
def decrypt( text ) | |
@key.send( "#{key_type}_decrypt", Base64.decode64( text ) ) | |
end | |
def private? | |
!@public | |
end | |
def public? | |
@public | |
end | |
def key_type | |
public? ? :public : :private | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment