Class: EncryptedAttributes::ShaCipher

Inherits:
EncryptedStrings::ShaCipher
  • Object
show all
Defined in:
lib/encrypted_attributes/sha_cipher.rb

Overview

Adds support for embedding salts in the encrypted value

Constant Summary

@@algorithm_lengths =

Tracks the lengths generated for each hashing algorithm

{
  'MD5' => 32,
  'SHA1' => 40,
  'SHA2' => 64,
  'SHA256' => 64,
  'SHA384' => 96,
  'SHA512' => 128
}

Class Attribute Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (ShaCipher) initialize(value, options = {})

Encrypts a string using a Secure Hash Algorithm (SHA), specifically SHA-1.

Configuration options:

  • :salt - Random bytes used as one of the inputs for generating the encrypted string

  • :embed_salt - Whether to embed the salt directly within the encrypted value. Default is false. This is useful for storing both the salt and the encrypted value in the same attribute.



30
31
32
33
34
35
36
37
38
39
# File 'lib/encrypted_attributes/sha_cipher.rb', line 30

def initialize(value, options = {}) #:nodoc:
  if @embed_salt = options.delete(:embed_salt) || self.class.default_embed_salt
    # The salt is at the end of the value
    algorithm = (options[:algorithm] || EncryptedStrings::ShaCipher.default_algorithm).upcase
    salt = value[@@algorithm_lengths[algorithm]..-1]
    options[:salt] = salt unless salt.blank?
  end
  
  super(options)
end

Class Attribute Details

+ (Object) default_embed_salt

Whether to embed the salt by default



6
7
8
# File 'lib/encrypted_attributes/sha_cipher.rb', line 6

def default_embed_salt
  @default_embed_salt
end

Instance Method Details

- (Object) encrypt(data)

Encrypts the data, embedding the salt at the end of the string if configured to do so



43
44
45
46
47
# File 'lib/encrypted_attributes/sha_cipher.rb', line 43

def encrypt(data)
  encrypted_data = super
  encrypted_data << salt if @embed_salt
  encrypted_data
end