@private
@param [Integer] size Size of data given. @return [Integer] Returns the AES encrypted size based on a given size.
# File lib/aws/s3/encryption_utils.rb, line 116 def get_encrypted_size size # The next multiple of 16 ((size / 16) + 1) * 16 end
Checks for any formatting problems for keys and initialization vectors
supported with EncryptionUtils.
# File lib/aws/s3/encryption_utils.rb, line 69 def check_encryption_materials mode, key rsa = OpenSSL::PKey::RSA case key when rsa unless key.private? or mode == :encrypt msg = "invalid key, #{rsa} requires a private key" raise ArgumentError, msg end when String # no problem else msg = "invalid key, must be an #{rsa} or a cipher key string" raise ArgumentError, msg end end
@param [OpenSSL::PKey::RSA, String] key Key used to encrypt.
@param [String] data Data to be encrypted.
@note Use #check_encryption_materials before this method to check
formatting of keys
@return [String] Returns the data decrypted with the key given.
# File lib/aws/s3/encryption_utils.rb, line 52 def decrypt data, key rsa = OpenSSL::PKey::RSA begin case key when rsa # Asymmetric Decryption key.private_decrypt(data) when String # Symmetric Decryption cipher = get_aes_cipher(:decrypt, :ECB, key) cipher.update(data) + cipher.final end rescue OpenSSL::Cipher::CipherError raise RuntimeError, "decryption failed, incorrect key?" end end
@param [OpenSSL::PKey::RSA, String] key Key used to encrypt.
@param [String] data Data to be encrypted.
@note Use #check_encryption_materials before this method to check
formatting of keys
@return [String] Returns the data encrypted with the key given.
# File lib/aws/s3/encryption_utils.rb, line 32 def encrypt data, key rsa = OpenSSL::PKey::RSA ## Encrypting data key case key when rsa # Asymmetric encryption key.public_encrypt(data) when String # Symmetric encryption cipher = get_aes_cipher(:encrypt, :ECB, key) cipher.update(data) + cipher.final end end
@param [OpenSSL::Cipher] cipher The cipher with configured key and iv.
@yield [String, String] key_iv_pair A randomly generated key, iv pair
for use with the given cipher. Sets the key and iv on the cipher.
# File lib/aws/s3/encryption_utils.rb, line 88 def generate_aes_key cipher, &block key_iv_pair = [cipher.random_key, cipher.random_iv] yield(key_iv_pair) if block_given? end
@param [Symbol] mode The encryption/decryption mode. Valid inputs are
:encrypt or :decrypt
@param [String] key Key for the cipher.
@param [String] iv IV for the cipher.
@return [OpenSSL::Cipher] Will return a configured +OpenSSL::Cipher+.
# File lib/aws/s3/encryption_utils.rb, line 101 def get_aes_cipher mode, block_mode, key = nil, iv = nil # If no key given, default to 256 bit cipher_size = (key) ? get_cipher_size(key.length) : 256 cipher = OpenSSL::Cipher.new("AES-#{cipher_size}-#{block_mode}") (mode == :encrypt) ? cipher.encrypt : cipher.decrypt cipher.key = key if key cipher.iv = iv if iv cipher end