Skip to content

Instantly share code, notes, and snippets.

@mks-m
Forked from wteuber/encrypt_decrypt.rb
Last active June 19, 2018 12:17
Show Gist options
  • Save mks-m/aa4c4e8c17725889f17222232ce03fb7 to your computer and use it in GitHub Desktop.
Save mks-m/aa4c4e8c17725889f17222232ce03fb7 to your computer and use it in GitHub Desktop.
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