Class: Ruar::Cipher

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

Instance Method Summary collapse

Constructor Details

#initializeCipher

Returns a new instance of Cipher.



5
6
7
# File 'lib/ruar/cipher.rb', line 5

def initialize
  @enable = false
end

Instance Method Details

#aeadObject



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

def aead
  @aead ||= OpenSSL::Cipher.new('aes-256-gcm')
end

#decrypt(data, auth_data: @auth_data, key: @key, iv: @iv, tag: @tag) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/ruar/cipher.rb', line 49

def decrypt(data, auth_data: @auth_data, key: @key, iv: @iv, tag: @tag)
  raise 'tag is truncated!' unless tag.bytesize == 16

  cipher = aead.decrypt
  cipher.key = key
  cipher.iv = iv
  cipher.auth_tag = tag
  cipher.auth_data = auth_data

  decrypted = cipher.update(Base64.decode64(data))
  decompressed = Ruar::Compression.decompress(decrypted)

  { decrypted: decompressed }
end

#enableObject



17
18
19
# File 'lib/ruar/cipher.rb', line 17

def enable
  @enable = true
end

#enable?Boolean

Returns:

  • (Boolean)


13
14
15
# File 'lib/ruar/cipher.rb', line 13

def enable?
  @enable
end

#encrypt(data, auth_data: @auth_data, key: @key, iv: @iv) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/ruar/cipher.rb', line 30

def encrypt(data, auth_data: @auth_data, key: @key, iv: @iv)
  cipher = aead.encrypt
  cipher.key = key
  cipher.iv = iv
  cipher.auth_data = auth_data

  compressed = Ruar::Compression.compress(data)
  encrypted = Base64.encode64(cipher.update(compressed) + cipher.final)
  tag = cipher.auth_tag

  {
    encrypted: encrypted,
    iv: iv,
    key: key,
    tag: tag,
    auth_data: auth_data
  }
end

#setup(key: nil, iv: nil, auth_data: nil, tag: nil) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/ruar/cipher.rb', line 21

def setup(key: nil, iv: nil, auth_data: nil, tag: nil)
  @key = key.nil? ? aead.random_key : Base64.decode64(key)
  @iv = iv.nil? ? aead.random_iv : Base64.decode64(iv)
  @auth_data = auth_data.nil? ? 'ruar_default_auth_data' : Base64.decode64(auth_data)
  @tag = tag.nil? ? 'ruar_invalid_auth_tag' : Base64.decode64(tag)

  self
end