Last active
September 20, 2022 16:50
-
-
Save ChunAllen/73f29043821dc92457b458ee6bb2ddc2 to your computer and use it in GitHub Desktop.
Encryption using AES-256-CBC with Rails
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
module Crypt | |
class << self | |
ENCRYPTION_KEY = Rails.application.secrets[:encryption_key] | |
ALGO = 'aes-256-cbc'.freeze | |
def encrypt(value) | |
crypt(:encrypt, value) | |
end | |
def decrypt(value) | |
crypt(:decrypt, value) | |
end | |
def crypt(cipher_method, value) | |
cipher = OpenSSL::Cipher.new(ALGO) | |
cipher.send(cipher_method) | |
cipher.pkcs5_keyivgen(ENCRYPTION_KEY) | |
result = cipher.update(value) | |
result << cipher.final | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment