Class: AttrCipher::Cipher

Inherits:
Object
  • Object
show all
Defined in:
lib/attr_cipher/cipher.rb

Constant Summary collapse

ALGORITHM =
"AES-256-CBC".freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(secret) ⇒ Cipher

Returns a new instance of Cipher.



11
12
13
# File 'lib/attr_cipher/cipher.rb', line 11

def initialize(secret)
  @secret = secret
end

Instance Attribute Details

#secretObject (readonly)

Returns the value of attribute secret.



9
10
11
# File 'lib/attr_cipher/cipher.rb', line 9

def secret
  @secret
end

Class Method Details

.decrypt(secret, value) ⇒ Object



45
46
47
# File 'lib/attr_cipher/cipher.rb', line 45

def self.decrypt(secret, value)
  new(secret).decrypt(value)
end

.encrypt(secret, value) ⇒ Object



49
50
51
# File 'lib/attr_cipher/cipher.rb', line 49

def self.encrypt(secret, value)
  new(secret).encrypt(value)
end

Instance Method Details

#cipher(mode, value) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/attr_cipher/cipher.rb', line 15

def cipher(mode, value)
  cipher = OpenSSL::Cipher.new(ALGORITHM).public_send(mode)
  digest = Digest::SHA256.digest(@secret)
  cipher.key = digest
  cipher.iv = digest[0...cipher.iv_len]
  cipher.update(value) + cipher.final
end

#decode(value) ⇒ Object



23
24
25
# File 'lib/attr_cipher/cipher.rb', line 23

def decode(value)
  Base64.decode64(value)
end

#decrypt(value) ⇒ Object



27
28
29
30
31
32
# File 'lib/attr_cipher/cipher.rb', line 27

def decrypt(value)
  raise ::AttrCipher::SecretTooShortException.new(
    "Secret must have at least 100 characters"
  ) if @secret.size < 100
  cipher(:decrypt, decode(value))
end

#encode(value) ⇒ Object



34
35
36
# File 'lib/attr_cipher/cipher.rb', line 34

def encode(value)
  Base64.encode64(value).chomp
end

#encrypt(value) ⇒ Object



38
39
40
41
42
43
# File 'lib/attr_cipher/cipher.rb', line 38

def encrypt(value)
  raise ::AttrCipher::SecretTooShortException.new(
    "Secret must have at least 100 characters"
  ) if @secret.size < 100
  encode(cipher(:encrypt, value))
end