Last active
April 1, 2020 14:39
-
-
Save alexishida/1b7f21d1f0f6eb9b16559bd0e0b4c2c0 to your computer and use it in GitHub Desktop.
Encrypt and Decrypt using Openssl Ruby
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
| require 'openssl' | |
| class CryptoService | |
| def encrypt(data,key) | |
| digest = Digest::SHA256.new | |
| digest.update(key) | |
| key = digest.digest | |
| cipher = OpenSSL::Cipher::AES.new(256, :CBC) | |
| cipher.encrypt | |
| cipher.key = key | |
| Base64.encode64(cipher.update(data) + cipher.final) | |
| end | |
| def decrypt(data,key) | |
| digest = Digest::SHA256.new | |
| digest.update(key) | |
| key = digest.digest | |
| decipher = OpenSSL::Cipher::AES.new(256, :CBC) | |
| decipher.decrypt | |
| decipher.key = key | |
| decipher.update(Base64.decode64(data)) + decipher.final | |
| end | |
| end | |
| data = "Very, very confidential data" | |
| key = 'dfa566d72971f2de23a1bb1a7e3f43d52s3d' | |
| crypto = CryptoService.new() | |
| texto = crypto.encrypt(data,key) | |
| puts texto | |
| plain = crypto.decrypt(texto,key) | |
| puts plain |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment