Class: Match::Encryption::MatchDataEncryption

Inherits:
Object
  • Object
show all
Defined in:
match/lib/match/encryption/encryption.rb

Constant Summary collapse

V1_PREFIX =
"Salted__"
V2_PREFIX =
"match_encrypted_v2__"

Instance Method Summary collapse

Instance Method Details

#decrypt(base64encoded_encrypted:, password:) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'match/lib/match/encryption/encryption.rb', line 108

def decrypt(base64encoded_encrypted:, password:)
  stored_data = Base64.decode64(base64encoded_encrypted)
  if stored_data.start_with?(V2_PREFIX)
    salt = stored_data[20..27]
    auth_tag = stored_data[28..43]
    data_to_decrypt = stored_data[44..-1]
    e = EncryptionV2.new
    e.decrypt(encrypted_data: data_to_decrypt, password: password, salt: salt, auth_tag: auth_tag)
  else
    salt = stored_data[8..15]
    data_to_decrypt = stored_data[16..-1]
    e = EncryptionV1.new
    begin
      # Note that we are not guaranteed to catch the decryption errors here if the password or the hash is wrong
      # as there's no integrity checks.
      # see https://github.com/fastlane/fastlane/issues/21663
      e.decrypt(encrypted_data: data_to_decrypt, password: password, salt: salt)
      # With the wrong hash_algorithm, there's here 0.4% chance that the decryption failure will go undetected
    rescue => _ex
      # With a wrong password, there's a 0.4% chance it will decrypt garbage and not fail
      fallback_hash_algorithm = "SHA256"
      e.decrypt(encrypted_data: data_to_decrypt, password: password, salt: salt, hash_algorithm: fallback_hash_algorithm)
    end
  end
end

#encrypt(data:, password:, version: 2) ⇒ Object



94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'match/lib/match/encryption/encryption.rb', line 94

def encrypt(data:, password:, version: 2)
  salt = SecureRandom.random_bytes(8)
  if version == 2
    e = EncryptionV2.new
    encryption = e.encrypt(data: data, password: password, salt: salt)
    encrypted_data = V2_PREFIX + salt + encryption[:auth_tag] + encryption[:encrypted_data]
  else
    e = EncryptionV1.new
    encryption = e.encrypt(data: data, password: password, salt: salt)
    encrypted_data = V1_PREFIX + salt + encryption[:encrypted_data]
  end
  Base64.encode64(encrypted_data)
end