module SecurizeString::CipherMethods::InstanceMethods
Adds instance methods for OpenSSL::Cipher support, including AES encryption, via inclusion of SecurizeString::CipherMethods
into a class.
Public Instance Methods
from_aes(key, iv)
click to toggle source
Given an AES key and init vector, AES-CBC decode the data.
# 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)
click to toggle source
Given an OpenSSL cipher name, a key, and an init vector, decrypt the data.
# 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)
click to toggle source
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.
# 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)
click to toggle source
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
# 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