module MySQLEncryption

Public Instance Methods

mysql_decrypt(s, key=$encryption_key) click to toggle source
# File lib/attr_encryption/mysql_encryption.rb, line 10
def mysql_decrypt(s, key=$encryption_key)
  return nil if s.blank?
  do_decrypt(s, mysql_key(key))
end
mysql_encrypt(s, key=$encryption_key) click to toggle source
# File lib/attr_encryption/mysql_encryption.rb, line 5
def mysql_encrypt(s, key=$encryption_key)
  return nil if s.blank?
  do_encrypt(s, mysql_key(key))
end

Protected Instance Methods

aes(m,k,t) click to toggle source
# File lib/attr_encryption/mysql_encryption.rb, line 17
def aes(m,k,t)
  (aes = OpenSSL::Cipher::AES128.new("ECB").send(m)).key = k
  aes.update(t) << aes.final
end
do_decrypt(text, key) click to toggle source
# File lib/attr_encryption/mysql_encryption.rb, line 26
def do_decrypt(text, key)
  aes(:decrypt, key, text)
end
do_encrypt(text, key) click to toggle source
# File lib/attr_encryption/mysql_encryption.rb, line 22
def do_encrypt(text, key)
  aes(:encrypt, key, text)
end
mysql_key(key) click to toggle source

This method returns a key based on the specified key that is 16 bytes in length. If the specified key is shorter than 16 bytes it is zero-padded to 16 bytes. If the specified key is longer 16 bytes, the bytes of the original key are folded back on itself using the XOR operator. This ensures that all the bytes in the original key are used, but the resulting key remains 16 bytes long.

Sheesh.

# File lib/attr_encryption/mysql_encryption.rb, line 40
def mysql_key(key)
  return nil if key.nil?
  final_key = "\0" * 16
  key.bytes.each_with_index do |b, i|
    buf = (final_key[i%16].bytes.first ^ b)
    final_key[i%16] = buf.chr
  end
  final_key
end