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



202
203
204
205
206
# File 'lib/pod4/encrypting.rb', line 202

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



193
194
195
196
197
# File 'lib/pod4/encrypting.rb', line 193

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_



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

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



141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/pod4/encrypting.rb', line 141

def map_to_interface
  return super if self.class.encryption_key.nil?

  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



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/pod4/encrypting.rb', line 164

def map_to_model(ot)
  return super(ot) if self.class.encryption_key.nil?

  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