Skip to content

Instantly share code, notes, and snippets.

@hudon
Last active August 29, 2015 14:20
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 hudon/1e1b395780351073486e to your computer and use it in GitHub Desktop.
Save hudon/1e1b395780351073486e to your computer and use it in GitHub Desktop.
hybrid encryption to encrypt large data with an rsa pubkey and aes
def self.encrypt(data, crt_pem)
cert = OpenSSL::X509::Certificate.new(crt_pem)
rsa = cert.public_key
aes = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
aes.encrypt
key = aes.random_key.unpack('H*')[0]
iv = aes.random_iv.unpack('H*')[0]
ciphertext = aes.update(data)
ciphertext << aes.final
key = rsa.public_encrypt(key)
iv = rsa.public_encrypt(iv)
[ciphertext, key, iv].map {|o| Base64.encode64(o)}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment