Sha256: 2a42d9fbb814907f91acc20e7818efcb59a25da85bb1afb2ec6c55d0e833f75c

Contents?: true

Size: 1.81 KB

Versions: 13

Compression:

Stored size: 1.81 KB

Contents

require 'digest/sha2'
require 'openssl'
require 'base64'

module CryptKeeper
  module Provider
    class Aes
      SEPARATOR = ":crypt_keeper:"

      # Public: The encryption key
      attr_accessor :key

      # Public: An instance of  OpenSSL::Cipher::Cipher
      attr_accessor :aes

      # Public: Initializes the class
      #
      #   options - A hash of options. :key is required
      def initialize(options = {})
        legacy
        @aes         = ::OpenSSL::Cipher::Cipher.new("AES-256-CBC")
        @aes.padding = 1

        key = options.fetch(:key) do
          raise ArgumentError, "Missing :key"
        end

        @key = Digest::SHA256.digest(key)
      end

      # Public: Encrypt a string
      #
      # Note: nil and empty strings are not encryptable with AES.
      # When they are encountered, the orignal value is returned.
      # Otherwise, returns the encrypted string
      def encrypt(value)
        return value if value == '' || value.nil?
        aes.encrypt
        aes.key = key
        Base64::encode64("#{aes.random_iv}#{SEPARATOR}#{aes.update(value.to_s) + aes.final}")
      end

      # Public: Decrypt a string
      #
      # Note: nil and empty strings are not encryptable with AES (and thus cannot be decrypted).
      # When they are encountered, the orignal value is returned.
      # Otherwise, returns the decrypted string
      def decrypt(value)
        return value if value == '' || value.nil?
        iv, value = Base64::decode64(value.to_s).split(SEPARATOR)
        aes.decrypt
        aes.key = key
        aes.iv  = iv
        aes.update(value) + aes.final
      end

      private

      def legacy
        unless ENV['CRYPT_KEEPER_IGNORE_LEGACY_DEPRECATION']
          warn "[DEPRECATION] AES Legacy is now deprecated. Please see http://git.io/uYcp2A"
        end
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
crypt_keeper-0.22.0 lib/crypt_keeper/provider/aes.rb
crypt_keeper-0.21.0 lib/crypt_keeper/provider/aes.rb
crypt_keeper-0.20.0 lib/crypt_keeper/provider/aes.rb
crypt_keeper-0.19.0 lib/crypt_keeper/provider/aes.rb
crypt_keeper-0.18.4 lib/crypt_keeper/provider/aes.rb
crypt_keeper-0.18.3 lib/crypt_keeper/provider/aes.rb
crypt_keeper-0.18.2 lib/crypt_keeper/provider/aes.rb
crypt_keeper-0.18.1 lib/crypt_keeper/provider/aes.rb
crypt_keeper-0.18.0 lib/crypt_keeper/provider/aes.rb
crypt_keeper-0.17.0 lib/crypt_keeper/provider/aes.rb
crypt_keeper-0.16.1 lib/crypt_keeper/provider/aes.rb
crypt_keeper-0.16.0 lib/crypt_keeper/provider/aes.rb
crypt_keeper-0.16.0.pre lib/crypt_keeper/provider/aes.rb