Class: Crypto::Key

Inherits:
Object
  • Object
show all
Defined in:
lib/crypto.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, size) ⇒ Key

Returns a new instance of Key.



13
14
15
16
17
# File 'lib/crypto.rb', line 13

def initialize(data, size)
  @public = (data =~ /^-----BEGIN (RSA|DSA) PRIVATE KEY-----$/).nil?
  @key = OpenSSL::PKey::RSA.new(data)
  @size = (size == 4096 ? 512 : 256)
end

Class Method Details

.from_file(filename, size = 4096) ⇒ Object



19
20
21
# File 'lib/crypto.rb', line 19

def self.from_file(filename, size = 4096)
  self.new(File.read(filename), size)
end

Instance Method Details

#decrypt(text) ⇒ Object



54
55
56
57
58
# File 'lib/crypto.rb', line 54

def decrypt(text)
  @key.send("#{key_type}_decrypt", text)
 rescue Exception => e
   puts_fail "RSA decrypt error: #{e.message}"
end

#decrypt_from_stream(data) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/crypto.rb', line 36

def decrypt_from_stream(data)
  encrypt_data = StringIO.new data
  encrypt_data.seek 0
  decrypt_data = ""

  while buf = encrypt_data.read(@size) do
    decrypt_data += decrypt(buf)
  end

  decrypt_data
end

#encrypt(text) ⇒ Object



48
49
50
51
52
# File 'lib/crypto.rb', line 48

def encrypt(text)
  @key.send("#{key_type}_encrypt", text)
rescue Exception => e
  puts_fail "RSA encrypt error: #{e.message}"
end

#encrypt_to_stream(data) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/crypto.rb', line 23

def encrypt_to_stream(data)
  encrypt_data = StringIO.new
  data = data.read if data.is_a? StringIO
  i = 0

  while buf = data[i..(i+=117)] do
    encrypt_data << encrypt(buf)
  end

  encrypt_data.seek 0
  encrypt_data
end

#key_typeObject



68
69
70
# File 'lib/crypto.rb', line 68

def key_type
  @public ? :public : :private
end

#private?Boolean

Returns:

  • (Boolean)


60
61
62
# File 'lib/crypto.rb', line 60

def private?
  !@public
end

#public?Boolean

Returns:

  • (Boolean)


64
65
66
# File 'lib/crypto.rb', line 64

def public?
  @public
end