Sha256: 9486a9b4a799d2bad1d1ced0de5bf8fd1eb60d3340bb9c090e87df2a7ba006cc

Contents?: true

Size: 1.7 KB

Versions: 2

Compression:

Stored size: 1.7 KB

Contents

module PluginAWeek #:nodoc:
  module EncryptedAttributes
    # Adds support for dynamically generated salts
    class ShaEncryptor < PluginAWeek::EncryptedStrings::ShaEncryptor
      # Encrypts a string using a Secure Hash Algorithm (SHA), specifically SHA-1.
      # 
      # The <tt>:start</tt> configuration option can be any one of the following types:
      # * +symbol+ - Calls the method on the object whose value is being encrypted
      # * +proc+ - A block that will be invoked, providing it with the object whose value is being encrypted
      # * +string+ - The actual salt value to use
      def initialize(object, value, operation, options = {}) #:nodoc:
        if operation == :write
          # Figure out the actual salt value
          if salt = options[:salt]
            options[:salt] =
              case salt
              when Symbol
                object.send(salt)
              when Proc
                salt.call(object)
              else
                salt
              end
          end
          
          # Track whether or not the salt was generated dynamically
          @dynamic_salt = salt != options[:salt]
          
          super(options)
        else
          # The salt is at the end of the value if it's dynamic
          salt = value[40..-1]
          if @dynamic_salt = !salt.blank?
            options[:salt] = salt 
          end
          
          super(options)
        end
      end
      
      # Encrypts the data, appending the salt to the end of the string if it
      # was created dynamically
      def encrypt(data)
        encrypted_data = Digest::SHA1.hexdigest(data + salt)
        encrypted_data << salt if @dynamic_salt
        encrypted_data
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
encrypted_attributes-0.1.2 lib/encrypted_attributes/sha_encryptor.rb
encrypted_attributes-0.1.3 lib/encrypted_attributes/sha_encryptor.rb