Skip to content

Instantly share code, notes, and snippets.

@zhouzhuojie
zhouzhuojie / crypto.rb
Last active September 27, 2017 00:41 — forked from bgreenlee/crypto.rb
Simple Ruby wrapper for encryption/decryption using OpenSSL
class Crypto
# encrypts data with the given key. returns a binary data with the
# unhashed random iv in the first 16 bytes
def self.encrypt(data, key)
cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
cipher.encrypt
cipher.key = key = Digest::SHA256.digest(key)
random_iv = cipher.random_iv
cipher.iv = Digest::SHA256.digest(random_iv + key)[0..15]
encrypted = cipher.update(data)