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



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

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

.encrypt(secret, value) ⇒ Object



43
44
45
# File 'lib/attr_cipher/cipher.rb', line 43

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
# File 'lib/attr_cipher/cipher.rb', line 27

def decrypt(value)
  cipher(:decrypt, decode(value))
end

#encode(value) ⇒ Object



31
32
33
# File 'lib/attr_cipher/cipher.rb', line 31

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

#encrypt(value) ⇒ Object



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

def encrypt(value)
  encode(cipher(:encrypt, value))
end