Class: EncryptedStrings::ShaCipher

Inherits:
Cipher
  • Object
show all
Defined in:
lib/encrypted_strings/sha_cipher.rb

Overview

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

Encrypting

To encrypt a string using an SHA cipher, the salt used to seed the algorithm must be specified. You can define the default for this value like so:

EncryptedStrings::ShaCipher.default_salt = 'secret'

If these configuration options are not passed in to #encrypt, then the default values will be used. You can override the default values like so:

password = 'shhhh'
password.encrypt(:sha, :salt => 'secret')  # => "ae645b35bb5dfea6c9133ac872e6adfa92a3c2bd"

Decrypting

SHA-encrypted strings cannot be decrypted. The only way to determine whether an unencrypted value is equal to an SHA-encrypted string is to encrypt the value with the same salt. For example,

password = 'shhhh'.encrypt(:sha, :salt => 'secret') # => "3b22cbe4acde873c3efc82681096f3ae69aff828"
input = 'shhhh'.encrypt(:sha, :salt => 'secret')    # => "3b22cbe4acde873c3efc82681096f3ae69aff828"
password == input                                   # => true

Class Attribute Summary collapse

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Cipher

#decrypt

Constructor Details

#initialize(options = {}) ⇒ ShaCipher

Creates a new cipher that uses an SHA encryption strategy.

Configuration options:

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

Raises:

  • (ArgumentError)


46
47
48
49
50
51
52
53
54
55
# File 'lib/encrypted_strings/sha_cipher.rb', line 46

def initialize(options = {})
  invalid_options = options.keys - [:salt]
  raise ArgumentError, "Unknown key(s): #{invalid_options.join(", ")}" unless invalid_options.empty?
  
  options = {:salt => ShaCipher.default_salt}.merge(options)
  
  self.salt = options[:salt].to_s
  
  super()
end

Class Attribute Details

.default_saltObject

The default salt value to use during encryption



32
33
34
# File 'lib/encrypted_strings/sha_cipher.rb', line 32

def default_salt
  @default_salt
end

Instance Attribute Details

#saltObject

The salt value to use for encryption



39
40
41
# File 'lib/encrypted_strings/sha_cipher.rb', line 39

def salt
  @salt
end

Instance Method Details

#can_decrypt?Boolean

Decryption is not supported

Returns:

  • (Boolean)


58
59
60
# File 'lib/encrypted_strings/sha_cipher.rb', line 58

def can_decrypt?
  false
end

#encrypt(data) ⇒ Object

Returns the encrypted value of the data



63
64
65
# File 'lib/encrypted_strings/sha_cipher.rb', line 63

def encrypt(data)
  Digest::SHA1.hexdigest(data + salt)
end