Class: Crypto::Key
- Inherits:
-
Object
- Object
- Crypto::Key
- Defined in:
- lib/crypto.rb
Class Method Summary collapse
Instance Method Summary collapse
- #decrypt(text) ⇒ Object
- #decrypt_from_stream(data) ⇒ Object
- #encrypt(text) ⇒ Object
- #encrypt_to_stream(data) ⇒ Object
-
#initialize(data, size) ⇒ Key
constructor
A new instance of Key.
- #key_type ⇒ Object
- #private? ⇒ Boolean
- #public? ⇒ Boolean
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.}" 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.}" 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_type ⇒ Object
68 69 70 |
# File 'lib/crypto.rb', line 68 def key_type @public ? :public : :private end |
#private? ⇒ Boolean
60 61 62 |
# File 'lib/crypto.rb', line 60 def private? !@public end |
#public? ⇒ Boolean
64 65 66 |
# File 'lib/crypto.rb', line 64 def public? @public end |