Module: AttributeQueryableEncrypted::PrefixAttributes::ClassMethods

Defined in:
lib/attribute_queryable_encrypted/prefix_attributes.rb

Instance Method Summary collapse

Instance Method Details

#attribute_queryable_encrypted(*attributes) ⇒ Object

Assigns a digest-hashed value to an attribute writer using a portion of the value assigned to each attribute's normal writer. The digest-hashed prefix can then be used to identify other objects with the same prefix without revealing the underlying value.

Example:

class HiddenValue
include AttributeQueryableEncrypted::PrefixAttributes
attr_writer :data
attr_accessor :prefix_data_digest
attribute_queryable_encrypted :data
end

hider = HiddenValue.new                                                        
                                                                             
hider.data = "This is a string"                                                
hider.prefix_data_digest                                                       
# => "a37010c994067764d86540bf479d93b4d0c3bb3955de7b61f951caf2fd0301b0"      

This technique is valuable when the queryable encrypted attribute is not persisted, or is persisted in a non-deterministic way (i.e. a salted, encrypted database column)

Options:

:length - an integer value length, or percentage expressed as a string ("72%") :prefix - prefix name for the storage accessor. Default is "prefix" :suffix - suffix name for the storage accessor. Defuault is "suffix" :encode - Base64 encode the digest hash, suitable for database persistence. Default is false.



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/attribute_queryable_encrypted/prefix_attributes.rb', line 51

def attribute_queryable_encrypted *attributes
  
  options = attrbute_queryable_encrypted_default_options.merge(attributes.extract_options!)
  
  attributes.each do |attribute|
    queryable_encrypted_attributes[attribute] = options
    class_eval do
      alias_method "unprefixed_#{attribute}=".to_sym, "#{attribute}=".to_sym

      define_method "#{attribute}=", lambda {|*args, &blk|
        send("#{[options[:prefix], attribute, options[:suffix]].join('_')}=".to_sym, prefix_encrypt(args[0], options))
        send("unprefixed_#{attribute}=".to_sym, *args, &blk)
      }
    end
  end
end

#prefix_encrypt(value, options) ⇒ Object



68
69
70
71
72
73
# File 'lib/attribute_queryable_encrypted/prefix_attributes.rb', line 68

def prefix_encrypt(value, options)
  prefix_encrypted_value = value.prefix(options[:length]).stretch_digest(options)
  # prefix_encrypted_value = [prefix_encrypted_value].pack("m*") if options[:encode]
  prefix_encrypted_value = Base64.strict_encode64(prefix_encrypted_value) if options[:encode]
  prefix_encrypted_value
end