Sha256: 4847c4404047e865efbaea404e275baad2465550524d48d7c39ae3cb6e864267

Contents?: true

Size: 1.11 KB

Versions: 4

Compression:

Stored size: 1.11 KB

Contents

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

module CryptKeeperProviders
  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 = {})
      @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
    #
    # Returns a string
    def encrypt(value)
      aes.encrypt
      aes.key = key
      iv      = rand.to_s
      aes.iv  = iv
      Base64::encode64("#{iv}#{SEPARATOR}#{aes.update(value.to_s) + aes.final}")
    end

    # Public: Decrypt a string
    #
    # Returns a string
    def decrypt(value)
      iv, value = Base64::decode64(value.to_s).split(SEPARATOR)
      aes.decrypt
      aes.key = key
      aes.iv  = iv
      aes.update(value) + aes.final
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
crypt_keeper_providers-0.5.0 lib/crypt_keeper_providers/aes.rb
crypt_keeper_providers-0.4.0 lib/crypt_keeper_providers/aes.rb
crypt_keeper_providers-0.3.0 lib/crypt_keeper_providers/aes.rb
crypt_keeper_providers-0.2.0 lib/crypt_keeper_providers/aes.rb