Skip to content

Instantly share code, notes, and snippets.

@madwork
Created April 17, 2013 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madwork/5405656 to your computer and use it in GitHub Desktop.
Save madwork/5405656 to your computer and use it in GitHub Desktop.
Cipher implementation
#!/usr/local/bin/ruby
#
# http://www.ruby-doc.org/stdlib-2.0/libdoc/openssl/rdoc/OpenSSL/Cipher.html
require 'base64'
require 'openssl'
# create the cipher for encrypting
cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
cipher.encrypt
# you will need to store these for later, in order to decrypt your data
key = "47d599c94173962bd10a5094186647226e3b8709"
iv = cipher.random_iv
# load them into the cipher
cipher.key = key
cipher.iv = iv
# encrypt the message
encrypted = cipher.update('madwork')
encrypted << cipher.final
puts "encrypted: #{Base64.strict_encode64(encrypted)}"
# now we create a sipher for decrypting
cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
cipher.decrypt
cipher.key = key
cipher.iv = iv
# and decrypt it
decrypted = cipher.update(encrypted)
decrypted << cipher.final
puts "decrypted: #{decrypted}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment