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

Instance Method Details

#from_aes(key, iv) ⇒ Object

Given an AES key and init vector, AES-CBC decode the data.



85
86
87
88
# File 'lib/securize_string/cipher_methods.rb', line 85

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.



65
66
67
68
69
70
71
72
73
# File 'lib/securize_string/cipher_methods.rb', line 65

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.



79
80
81
82
# File 'lib/securize_string/cipher_methods.rb', line 79

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


53
54
55
56
57
58
59
60
61
# File 'lib/securize_string/cipher_methods.rb', line 53

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