Class: EncryptAttr::Encryptor

Inherits:
Object
  • Object
show all
Defined in:
lib/encrypt_attr/encryptor.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(secret_token) ⇒ Encryptor

Returns a new instance of Encryptor.



18
19
20
# File 'lib/encrypt_attr/encryptor.rb', line 18

def initialize(secret_token)
  @secret_token = secret_token
end

Instance Attribute Details

#secret_tokenObject (readonly)

Set the encryptor’s secret token.



16
17
18
# File 'lib/encrypt_attr/encryptor.rb', line 16

def secret_token
  @secret_token
end

Class Method Details

.decrypt(secret_token, value) ⇒ Object



11
12
13
# File 'lib/encrypt_attr/encryptor.rb', line 11

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

.encrypt(secret_token, value) ⇒ Object



7
8
9
# File 'lib/encrypt_attr/encryptor.rb', line 7

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

Instance Method Details

#cipher(mode, value) ⇒ Object



30
31
32
33
34
35
# File 'lib/encrypt_attr/encryptor.rb', line 30

def cipher(mode, value)
  cipher = OpenSSL::Cipher.new('AES-256-CBC').public_send(mode)
  cipher.key = Digest::SHA256.digest(secret_token)
  cipher.iv = Digest::SHA256.digest(secret_token)
  cipher.update(value) + cipher.final
end

#decode(value) ⇒ Object



41
42
43
# File 'lib/encrypt_attr/encryptor.rb', line 41

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

#decrypt(value) ⇒ Object



26
27
28
# File 'lib/encrypt_attr/encryptor.rb', line 26

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

#encode(value) ⇒ Object



37
38
39
# File 'lib/encrypt_attr/encryptor.rb', line 37

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

#encrypt(value) ⇒ Object



22
23
24
# File 'lib/encrypt_attr/encryptor.rb', line 22

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