2018-10-29 12:06:45 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Gitlab
|
|
|
|
module CryptoHelper
|
|
|
|
extend self
|
|
|
|
|
|
|
|
AES256_GCM_OPTIONS = {
|
|
|
|
algorithm: 'aes-256-gcm',
|
2021-02-01 19:09:14 -05:00
|
|
|
key: Settings.attr_encrypted_db_key_base_32
|
2018-10-29 12:06:45 -04:00
|
|
|
}.freeze
|
|
|
|
|
2021-02-01 19:09:14 -05:00
|
|
|
AES256_GCM_IV_STATIC = Settings.attr_encrypted_db_key_base_12
|
|
|
|
|
2018-10-29 12:06:45 -04:00
|
|
|
def sha256(value)
|
|
|
|
salt = Settings.attr_encrypted_db_key_base_truncated
|
|
|
|
::Digest::SHA256.base64digest("#{value}#{salt}")
|
|
|
|
end
|
|
|
|
|
2021-02-01 19:09:14 -05:00
|
|
|
def aes256_gcm_encrypt(value, nonce: nil)
|
|
|
|
aes256_gcm_encrypt_using_static_nonce(value)
|
2018-10-29 12:06:45 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def aes256_gcm_decrypt(value)
|
|
|
|
return unless value
|
|
|
|
|
2021-03-23 14:09:05 -04:00
|
|
|
nonce = AES256_GCM_IV_STATIC
|
2018-10-29 12:06:45 -04:00
|
|
|
encrypted_token = Base64.decode64(value)
|
2021-02-01 19:09:14 -05:00
|
|
|
decrypted_token = Encryptor.decrypt(AES256_GCM_OPTIONS.merge(value: encrypted_token, iv: nonce))
|
|
|
|
decrypted_token
|
|
|
|
end
|
|
|
|
|
|
|
|
def aes256_gcm_encrypt_using_static_nonce(value)
|
|
|
|
create_encrypted_token(value, AES256_GCM_IV_STATIC)
|
|
|
|
end
|
|
|
|
|
|
|
|
def read_only?
|
|
|
|
Gitlab::Database.read_only?
|
|
|
|
end
|
|
|
|
|
|
|
|
def create_encrypted_token(value, iv)
|
|
|
|
encrypted_token = Encryptor.encrypt(AES256_GCM_OPTIONS.merge(value: value, iv: iv))
|
|
|
|
Base64.strict_encode64(encrypted_token)
|
2018-10-29 12:06:45 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|