Skip to content

Instantly share code, notes, and snippets.

@apeiros
Last active August 29, 2015 14:00
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 apeiros/11392469 to your computer and use it in GitHub Desktop.
Save apeiros/11392469 to your computer and use it in GitHub Desktop.
What's wrong in crypto - compare
### The stuff to encrypt
data = 'hello world!'
password = 'test123'
# Note: all 3 implementations are supposed to do exactly the same
### Raw OpenSSL
# Decisions, decisions, decisions...
cipher = 'AES-256-CBC' # which ciphers are not trivially broken?
salt_length = 64 # what's a good length?
key_length = 64 # what's a good length?
digest_length = 40 # found experimentally
iterations = 20_000 # taken the number from the docs - how do I know what's a good number?
# Implementation
cipher = OpenSSL::Cipher::Cipher.new(cipher)
salt = SecureRandom.random_bytes(salt_length)
key = OpenSSL::PKCS5.pbkdf2_hmac_sha1(password, salt, iterations, key_length)
iv = cipher.random_iv
cipher.encrypt
cipher.key = key
cipher.iv = iv
encrypted = cipher.update(data)+cipher.final
digest = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA1.new, key, encrypted)
# And now, where do I store iv, digest and salt?
### Ruby on Rails 4.1 (http://api.rubyonrails.org/classes/ActiveSupport/MessageEncryptor.html)
require 'active_support/message_encryptor'
salt = SecureRandom.random_bytes(64)
key = ActiveSupport::KeyGenerator.new(password).generate_key(salt)
crypt = ActiveSupport::MessageEncryptor.new(key)
encrypted = crypt.encrypt_and_sign(data) # Better, takes care of storing salt, iv and digest in the encrypted data
### How I think it should be, because there's a close to zero chance to fuck things up on my end
require 'encryption' # https://gist.github.com/apeiros/11374740
encrypted = Encryption.encrypt(data: data, password: password) # Why should it be any more complicated than this? Seriously?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment