Last active
September 9, 2020 02:15
-
-
Save shobhitic/915fb971a0af5666ac575d09155332c0 to your computer and use it in GitHub Desktop.
Simple encryption and decryption function for Ruby on Rails 5.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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