Skip to content

Instantly share code, notes, and snippets.

@Inversion-des
Created December 9, 2024 15:35
Show Gist options
  • Save Inversion-des/47f4332c16b693721e85b72e173b78a7 to your computer and use it in GitHub Desktop.
Save Inversion-des/47f4332c16b693721e85b72e173b78a7 to your computer and use it in GitHub Desktop.
require 'openssl'
require 'base64'
# AES256 encryption
def aes_encrypt(text, key)
cipher = get_cipher.tap { _1.encrypt; _1.key = key }
iv = cipher.random_iv # 16 bytes
cipher_text = cipher.update(text) + cipher.final
# *ensure there is no newline char in the encoded text
Base64.strict_encode64(iv + cipher_text)
end
def aes_decrypt(encoded_text, key)
decoded_text = Base64.decode64(encoded_text)
iv, cipher_text = decoded_text.then { [_1[0..15], _1[16..]] }
cipher = get_cipher.tap { _1.decrypt; _1.key = key; _1.iv = iv }
cipher.update(cipher_text) + cipher.final
end
def get_cipher
OpenSSL::Cipher::AES256.new(:CBC)
end
# predefined text and key for demo
text = "This is a secret message."
key = "12345678901234567890123456789012" # 32-byte key
puts "Original text: #{text}"
encrypted_text = aes_encrypt(text, key)
puts "Encrypted text: #{encrypted_text}"
decrypted_text = aes_decrypt(encrypted_text, key)
puts "Decrypted text: #{decrypted_text}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment