Class: Keyring::Encryptor::AES::Base

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

Direct Known Subclasses

AES128CBC, AES192CBC, AES256CBC, AES256GCM

Class Method Summary collapse

Class Method Details

.build_cipherObject



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

def self.build_cipher
  OpenSSL::Cipher.new(cipher_name)
end

.decrypt(key, message) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/keyring/encryptor/aes.rb', line 34

def self.decrypt(key, message)
  cipher = build_cipher
  iv_size = cipher.random_iv.size
  cipher.decrypt

  message = Base64.strict_decode64(message)

  hmac = message[0...32]

  encrypted_payload = message[32..-1]
  expected_hmac = hmac_digest(key.signing_key, encrypted_payload)

  unless verify_signature(expected_hmac, hmac)
    raise InvalidAuthentication,
          "Expected HMAC to be " \
          "#{Base64.strict_encode64(expected_hmac)}; " \
          "got #{Base64.strict_encode64(hmac)} instead"
  end

  auth_tag = ""
  auth_tag = encrypted_payload[0...16] if support_auth_data?
  iv = encrypted_payload[auth_tag.size...(auth_tag.size + iv_size)]
  encrypted = encrypted_payload[(auth_tag.size + iv_size)..-1]

  cipher.iv = iv
  cipher.key = key.encryption_key

  if support_auth_data?
    cipher.auth_data = ""
    cipher.auth_tag = auth_tag
  end

  cipher.update(encrypted) + cipher.final
end

.encrypt(key, message) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/keyring/encryptor/aes.rb', line 19

def self.encrypt(key, message)
  cipher = build_cipher
  cipher.encrypt
  iv = cipher.random_iv
  cipher.iv  = iv
  cipher.key = key.encryption_key
  cipher.auth_data = "" if support_auth_data?
  encrypted = cipher.update(message) + cipher.final
  auth_tag = ""
  auth_tag = cipher.auth_tag if support_auth_data?
  hmac = hmac_digest(key.signing_key, "#{auth_tag}#{iv}#{encrypted}")

  Base64.strict_encode64("#{hmac}#{auth_tag}#{iv}#{encrypted}")
end

.hmac_digest(key, bytes) ⇒ Object



69
70
71
# File 'lib/keyring/encryptor/aes.rb', line 69

def self.hmac_digest(key, bytes)
  OpenSSL::HMAC.digest("sha256", key, bytes)
end

.key_sizeObject



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

def self.key_size
  @key_size ||= build_cipher.key_len
end

.support_auth_data?Boolean

Returns:

  • (Boolean)


15
16
17
# File 'lib/keyring/encryptor/aes.rb', line 15

def self.support_auth_data?
  false
end

.verify_signature(expected, actual) ⇒ Object



73
74
75
76
77
78
79
80
# File 'lib/keyring/encryptor/aes.rb', line 73

def self.verify_signature(expected, actual)
  expected_bytes = expected.bytes.to_a
  actual_bytes = actual.bytes.to_a

  actual_bytes.inject(0) do |accum, byte|
    accum | byte ^ expected_bytes.shift
  end.zero?
end