/
crypto.rb
46 lines (37 loc) · 1.08 KB
/
crypto.rb
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
43
44
45
46
require 'openssl'
module ActsAsEncryptable
# Originally posted by Tobias Lütke
# http://blog.leetsoft.com/2006/03/14/simple-encryption
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
end