Last active
August 29, 2015 14:20
-
-
Save hudon/1e1b395780351073486e to your computer and use it in GitHub Desktop.
hybrid encryption to encrypt large data with an rsa pubkey and aes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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