Module: SecurizeString::CipherMethods::InstanceMethods
- Defined in:
- lib/securize_string/cipher_methods.rb
Overview
Adds instance methods for OpenSSL::Cipher support, including AES encryption, via inclusion of SecurizeString::CipherMethods into a class.
Instance Method Summary collapse
-
#from_aes(key, iv) ⇒ Object
Given an AES key and init vector, AES-CBC decode the data.
-
#from_cipher(cipher_name, key, iv) ⇒ Object
Given an OpenSSL cipher name, a key, and an init vector, decrypt the data.
-
#to_aes(key, iv) ⇒ Object
Given an AES key and initialization vector, AES-CBC encode the data.
-
#to_cipher(cipher_name, key, iv) ⇒ Object
Given an OpenSSL cipher name, a key, and initialization vector, encrypt the data.
Instance Method Details
#from_aes(key, iv) ⇒ Object
Given an AES key and init vector, AES-CBC decode the data.
114 115 116 117 |
# File 'lib/securize_string/cipher_methods.rb', line 114 def from_aes(key, iv) key_len = (key.bytesize * 8) return self.class.new( from_cipher("aes-#{key_len}-cbc", key, iv) ) end |
#from_cipher(cipher_name, key, iv) ⇒ Object
Given an OpenSSL cipher name, a key, and an init vector, decrypt the data.
94 95 96 97 98 99 100 101 102 |
# File 'lib/securize_string/cipher_methods.rb', line 94 def from_cipher(cipher_name, key, iv) cipher = OpenSSL::Cipher.new(cipher_name) cipher.decrypt # MUST set the mode BEFORE setting the key and iv! cipher.key = key cipher.iv = iv msg = cipher.update(self.to_s) msg << cipher.final return self.class.new(msg) end |
#to_aes(key, iv) ⇒ Object
Given an AES key and initialization vector, AES-CBC encode the data.
Note that one normally never wants to use the same key and iv combination on two different messages as this weakens the security.
108 109 110 111 |
# File 'lib/securize_string/cipher_methods.rb', line 108 def to_aes(key, iv) key_len = (key.bytesize * 8) return self.class.new( to_cipher("aes-#{key_len}-cbc", key, iv) ) end |
#to_cipher(cipher_name, key, iv) ⇒ Object
Given an OpenSSL cipher name, a key, and initialization vector, encrypt the data.
Use OpenSSL::Cipher.ciphers to get a list of available cipher names.
To generate a new key and iv, do the following:
cipher = OpenSSL::Cipher::Cipher.new(cipher_name)
cipher.encrypt
key = cipher.random_key
iv = cipher.random_iv
82 83 84 85 86 87 88 89 90 |
# File 'lib/securize_string/cipher_methods.rb', line 82 def to_cipher(cipher_name, key, iv) cipher = OpenSSL::Cipher.new(cipher_name) cipher.encrypt # MUST set the mode BEFORE setting the key and iv! cipher.key = key cipher.iv = iv msg = cipher.update(self.to_s) msg << cipher.final return self.class.new(msg) end |