Skip to content

Instantly share code, notes, and snippets.

@garside
Created May 27, 2020 15:18
Show Gist options
  • Save garside/8ebc8c07404e3129681845faf8613cfe to your computer and use it in GitHub Desktop.
Save garside/8ebc8c07404e3129681845faf8613cfe to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
# This assumes you use rails credentials for the secret key, if not change KEY_BASE to your key location
# Also assumes you have the rails/config gem setup with a something like the following:
#
# cipher:
# salt: "\x87\xB2\x99\x14\xAA?\xA6;\xA3\x11^\xAB\xBE\x1C\x99\rl\xF4r\xCF\x91\x13\xC1\xAC\xD8HT\x1E\xA8\x04h\x95"
#
# You can (and should, don't use this one above!) generate your own salt using:
#
# SecureRandom.random_bytes(32)
#
# You might want to put it into your credentials file I dunno, I use a different salt per environment.
#
# Expected use:
#
# user = User.find(user_id)
# user.encrypted_api_key # => "s0m3-3nCRyp+3d-v4lu3"
# CipherService.decipher(user.encrypted_api_key) # => "some_unencrypted_value"
#
# user.update!(encrypted_api_key: CipherService.encipher("new_unencrypted_value"))
# user.encrypted_api_key # => "n3w-enCrYp+3d-v4lu3"
class CipherService
include Singleton
class << self
delegate :encipher, :decipher, to: :instance
end
KEY_BASE = Rails.application.credentials.secret_key_base
SALT = Settings.cipher.salt
KEY = ActiveSupport::KeyGenerator.new(KEY_BASE).generate_key(SALT, ActiveSupport::MessageEncryptor.key_len).freeze
private_constant :KEY_BASE, :SALT, :KEY
def encipher(value)
cipher.encrypt_and_sign(value)
end
def decipher(value)
cipher.decrypt_and_verify(value)
end
private
def cipher
@cipher ||= ActiveSupport::MessageEncryptor.new(KEY)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment