public
Description: The open source social networking platform in Ruby on Rails from the author of RailsSpace
Homepage: http://insoshi.com
Clone URL: git://github.com/insoshi/insoshi.git
Michael Hartl (author)
Wed Apr 23 19:56:22 -0700 2008
commit  593cafd209abbfb0bc2dc29960f8319d5deb87f7
tree    e84a830cced7a0185b389b13d998727dc0cbddb6
parent  083a98a234000519ac920168d428a17520607a17
insoshi / config / initializers / crypto.rb
100644 42 lines (33 sloc) 0.91 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
require 'openssl'
 
module Crypto
  
  def self.create_keys(priv = "rsa_key", pub = "#{priv}.pub", bits = 1024)
    private_key = OpenSSL::PKey::RSA.new(bits)
    File.open(priv, "w+") { |fp| fp << private_key.to_s }
    File.open(pub, "w+") { |fp| fp << private_key.public_key.to_s }
    private_key
  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