Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simply encrypt and decrypt Strings in ruby.
require 'openssl'
require 'base64'
# key and iv stored in configs, generated using:
# cipher = OpenSSL::Cipher::Cipher.new('AES-256-CBC').encrypt
# key = cipher.random_key
# iv = cipher.random_iv
def encrypt_id(key, iv, id)
cipher = OpenSSL::Cipher::Cipher.new('AES-256-CBC').encrypt
cipher.key = key
cipher.iv = iv
encrypted_binary = cipher.update(id.to_s(36)) + cipher.final
Base64.urlsafe_encode64(encrypted_binary)
end
def decrypt_id(key, iv, eid)
cipher = OpenSSL::Cipher::Cipher.new('AES-256-CBC').decrypt
cipher.key = key
cipher.iv = iv
decrypted_binary = Base64.urlsafe_decode64(eid)
(cipher.update(decrypted_binary) + cipher.final).to_i(36)
end
# example:
cipher = OpenSSL::Cipher::Cipher.new('AES-256-CBC').encrypt
key = cipher.random_key
iv = cipher.random_iv
id = 876345875645
eid = encrypt_id(key, iv, id)
decrypt_id('guess', eid)
decrypt_id(key, iv, eid)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.