Class: Slosilo::Symmetric

Inherits:
Object
  • Object
show all
Defined in:
lib/slosilo/symmetric.rb

Constant Summary collapse

VERSION_MAGIC =
'G'
TAG_LENGTH =
16

Instance Method Summary collapse

Constructor Details

#initializeSymmetric

Returns a new instance of Symmetric.



6
7
8
9
# File 'lib/slosilo/symmetric.rb', line 6

def initialize
  @cipher = OpenSSL::Cipher.new 'aes-256-gcm' # NB: has to be lower case for whatever reason.
  @cipher_mutex = Mutex.new
end

Instance Method Details

#cipher_nameObject

This lets us do a final sanity check in migrations from older encryption versions



12
13
14
# File 'lib/slosilo/symmetric.rb', line 12

def cipher_name
  @cipher.name
end

#decrypt(ciphertext, opts = {}) ⇒ Object



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

def decrypt ciphertext, opts = {}
  version, tag, iv, ctext = unpack ciphertext

  raise "Invalid version magic: expected #{VERSION_MAGIC} but was #{version}" unless version == VERSION_MAGIC

  # All of these operations in OpenSSL must occur atomically, so we
  # synchronize their access to make this step thread-safe.
  @cipher_mutex.synchronize do
    @cipher.reset
    @cipher.decrypt
    @cipher.key = opts[:key]
    @cipher.iv = iv
    @cipher.auth_tag = tag
    @cipher.auth_data = opts[:aad] || ""
    @cipher.update(ctext) + @cipher.final
  end
end

#encrypt(plaintext, opts = {}) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/slosilo/symmetric.rb', line 16

def encrypt plaintext, opts = {}
  # All of these operations in OpenSSL must occur atomically, so we
  # synchronize their access to make this step thread-safe.
  @cipher_mutex.synchronize do
    @cipher.reset
    @cipher.encrypt
    @cipher.key = (opts[:key] or raise("missing :key option"))
    @cipher.iv = iv = random_iv
    @cipher.auth_data = opts[:aad] || "" # Nothing good happens if you set this to nil, or don't set it at all
    ctext = @cipher.update(plaintext) + @cipher.final
    tag = @cipher.auth_tag(TAG_LENGTH)
    "#{VERSION_MAGIC}#{tag}#{iv}#{ctext}"
  end
end

#random_ivObject



49
50
51
# File 'lib/slosilo/symmetric.rb', line 49

def random_iv
  @cipher.random_iv
end

#random_keyObject



53
54
55
# File 'lib/slosilo/symmetric.rb', line 53

def random_key
  @cipher.random_key
end