Skip to content

Instantly share code, notes, and snippets.

@shobhitic
Last active September 9, 2020 02:15
Show Gist options
  • Save shobhitic/915fb971a0af5666ac575d09155332c0 to your computer and use it in GitHub Desktop.
Save shobhitic/915fb971a0af5666ac575d09155332c0 to your computer and use it in GitHub Desktop.
Simple encryption and decryption function for Ruby on Rails 5.
# Assuming your Secret Key Base is in Rails.application.secrets.secret_key_base
def encrypt text
text = text.to_s unless text.is_a? String
len = ActiveSupport::MessageEncryptor.key_len
salt = SecureRandom.hex len
key = ActiveSupport::KeyGenerator.new(Rails.application.secrets.secret_key_base).generate_key salt, len
crypt = ActiveSupport::MessageEncryptor.new key
encrypted_data = crypt.encrypt_and_sign text
"#{salt}$$#{encrypted_data}"
end
def decrypt text
salt, data = text.split "$$"
len = ActiveSupport::MessageEncryptor.key_len
key = ActiveSupport::KeyGenerator.new(Rails.application.secrets.secret_key_base).generate_key salt, len
crypt = ActiveSupport::MessageEncryptor.new key
crypt.decrypt_and_verify data
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment