Module: Pod4::Encrypting::InstanceMethods

Defined in:
lib/pod4/encrypting.rb

Instance Method Summary collapse

Instance Method Details

#decrypt(string) ⇒ Object

Public facing manual decryption, compatible with the current model



195
196
197
198
199
# File 'lib/pod4/encrypting.rb', line 195

def decrypt(string)
  cipher = get_cipher(:decrypt)
  iv     = use_iv? ? encryption_iv : nil
  crypt(cipher, :decrypt, iv, string)
end

#encrypt(string) ⇒ Object

Public facing manual encryption, compatible with the current model



186
187
188
189
190
# File 'lib/pod4/encrypting.rb', line 186

def encrypt(string)
  cipher = get_cipher(:encrypt)
  iv     = use_iv? ? encryption_iv : nil
  crypt(cipher, :encrypt, iv, string)
end

#encryption_ivObject

The value of the IV field (whatever it is) _as currently stored on the model_



178
179
180
181
# File 'lib/pod4/encrypting.rb', line 178

def encryption_iv
  return nil unless use_iv?
  instance_variable_get( "@#{self.class.encryption_iv_column}".to_sym )
end

#map_to_interfaceObject

When mapping to the interface, encrypt the encryptable columns from the model



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/pod4/encrypting.rb', line 138

def map_to_interface
  hash   = super.to_h
  cipher = get_cipher(:encrypt)

  # Each time we write, we set a new IV. We must also set it on the hash to go to the
  # interface, where it must be base64 encoded, just like the encrypted columns.
  if use_iv? 
    set_encryption_iv( cipher.random_iv )
    hash[self.class.encryption_iv_column] = Base64.strict_encode64(encryption_iv)
  end

  self.class.encryption_columns.each do |col|
    hash[col] = crypt(cipher, :encrypt, encryption_iv, hash[col])
  end

  Octothorpe.new(hash)
end

#map_to_model(ot) ⇒ Object

When mapping to the model, decrypt the encrypted columns from the interface



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/pod4/encrypting.rb', line 159

def map_to_model(ot)
  hash   = ot.to_h
  cipher = get_cipher(:decrypt)

  # The IV column is not in columns, so we need to de-base-64 it and set it on the model here
  if use_iv? && (iv64 = hash[self.class.encryption_iv_column])
    set_encryption_iv Base64.strict_decode64(iv64)
  end

  self.class.encryption_columns.each do |col|
    hash[col] = crypt(cipher, :decrypt, encryption_iv, hash[col])
  end

  super Octothorpe.new(hash)
end