Skip to content

Instantly share code, notes, and snippets.

@bcavileer
Created January 9, 2024 18:24
Show Gist options
  • Select an option

  • Save bcavileer/67de76eaa437049cd3269855f9d3dcfc to your computer and use it in GitHub Desktop.

Select an option

Save bcavileer/67de76eaa437049cd3269855f9d3dcfc to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require 'base64'
require 'openssl'
require 'securerandom'
def decrypt_data(encrypted_data, encryption_key)
cipher = OpenSSL::Cipher.new('AES-256-CBC')
cipher.decrypt
cipher.key = encryption_key
decrypted_data = cipher.update(encrypted_data) + cipher.final
decrypted_data
end
def encrypt_data(data, encryption_key)
cipher = OpenSSL::Cipher.new('AES-256-CBC')
cipher.encrypt
cipher.key = encryption_key
encrypted_data = cipher.update(data) + cipher.final
encrypted_data
end
data_to_encrypt = 'Sensitive Data'
puts "Date To Encrypt: #{data_to_encrypt}"
encryption_key = SecureRandom.alphanumeric(32) # Generate random encryption key
puts "Encryption Key: #{encryption_key}"
encrypted_data = encrypt_data(data_to_encrypt, encryption_key)
puts "Base64 Encoded Encrypted Data: #{Base64.encode64 encrypted_data}"
decrypted_data = decrypt_data(encrypted_data, encryption_key)
puts "Decrypted Data: #{decrypted_data}"
unless decrypted_data == data_to_encrypt
raise 'oops something went wrong'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment