Created
May 6, 2021 04:55
-
-
Save TheRusskiy/e2dfb2b93464d864efa7b64ed7edee32 to your computer and use it in GitHub Desktop.
Text Encryption in Ruby on Rails
This file contains hidden or 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
class TextEncryptor | |
class << self | |
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(secret).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(secret).generate_key salt, len | |
crypt = ActiveSupport::MessageEncryptor.new key | |
crypt.decrypt_and_verify data | |
end | |
private | |
def secret | |
Rails.application.secrets.secret_key_base | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment