Sha256: 58009dc4978e23f8720aeab2ff48bbaae4980c74b2897b9881ea293e335bd3f0

Contents?: true

Size: 1.54 KB

Versions: 28

Compression:

Stored size: 1.54 KB

Contents

# frozen_string_literal: true

module Prefab
  class Encryption
    CIPHER_TYPE = "aes-256-gcm" # 32/12
    SEPARATOR = "--"

    # Hexadecimal format ensures that generated keys are representable with
    # plain text
    #
    # To convert back to the original string with the desired length:
    #   [ value ].pack("H*")
    def self.generate_new_hex_key
      generate_random_key.unpack("H*")[0]
    end

    def initialize(key_string_hex)
      @key = [key_string_hex].pack("H*")
    end

    def encrypt(clear_text)
      cipher = OpenSSL::Cipher.new(CIPHER_TYPE)
      cipher.encrypt
      iv = cipher.random_iv

      # load them into the cipher
      cipher.key = @key
      cipher.iv = iv
      cipher.auth_data = ""

      # encrypt the message
      encrypted = cipher.update(clear_text)
      encrypted << cipher.final
      tag = cipher.auth_tag

      # pack and join
      [encrypted, iv, tag].map { |p| p.unpack("H*")[0] }.join(SEPARATOR)
    end

    def decrypt(encrypted_string)
      unpacked_parts = encrypted_string.split(SEPARATOR).map { |p| [p].pack("H*") }

      cipher = OpenSSL::Cipher.new(CIPHER_TYPE)
      cipher.decrypt
      cipher.key = @key
      cipher.iv = unpacked_parts[1]
      cipher.auth_tag = unpacked_parts[2]

      # and decrypt it
      decrypted = cipher.update(unpacked_parts[0])
      decrypted << cipher.final
      decrypted
    end

    private

    def self.generate_random_key
      SecureRandom.random_bytes(key_length)
    end

    def self.key_length
      OpenSSL::Cipher.new(CIPHER_TYPE).key_len
    end
  end
end

Version data entries

28 entries across 28 versions & 1 rubygems

Version Path
prefab-cloud-ruby-1.8.7 lib/prefab/encryption.rb
prefab-cloud-ruby-1.8.6 lib/prefab/encryption.rb
prefab-cloud-ruby-1.8.5 lib/prefab/encryption.rb
prefab-cloud-ruby-1.8.4 lib/prefab/encryption.rb
prefab-cloud-ruby-1.8.3 lib/prefab/encryption.rb
prefab-cloud-ruby-1.8.2 lib/prefab/encryption.rb
prefab-cloud-ruby-1.8.1 lib/prefab/encryption.rb
prefab-cloud-ruby-1.8.0 lib/prefab/encryption.rb
prefab-cloud-ruby-1.7.2 lib/prefab/encryption.rb
prefab-cloud-ruby-1.7.1 lib/prefab/encryption.rb
prefab-cloud-ruby-1.7.0 lib/prefab/encryption.rb
prefab-cloud-ruby-1.6.2 lib/prefab/encryption.rb
prefab-cloud-ruby-1.6.1 lib/prefab/encryption.rb
prefab-cloud-ruby-1.6.0 lib/prefab/encryption.rb
prefab-cloud-ruby-1.5.1 lib/prefab/encryption.rb
prefab-cloud-ruby-1.6.0.pre2 lib/prefab/encryption.rb
prefab-cloud-ruby-1.6.0.pre1 lib/prefab/encryption.rb
prefab-cloud-ruby-0 lib/prefab/encryption.rb
prefab-cloud-ruby-1.5.0 lib/prefab/encryption.rb
prefab-cloud-ruby-1.4.5 lib/prefab/encryption.rb