Sha256: d0f2b90369d5bd521b54a18f513fc2dae7fd259e251105af82e97ba1a9ee9bc1

Contents?: true

Size: 954 Bytes

Versions: 4

Compression:

Stored size: 954 Bytes

Contents

require "openssl"
require "base64"

module Kafkr
  class Encryptor
    ALGORITHM = "aes-256-cbc"

    def initialize
      @key = Base64.decode64(ENV["KAFKR_ENCRYPTION_KEY"])
    end

    def encrypt(data)
      cipher = OpenSSL::Cipher.new(ALGORITHM)
      cipher.encrypt
      cipher.key = @key
      iv = cipher.random_iv
      encrypted_data = cipher.update(data) + cipher.final
      encrypted_data = Base64.strict_encode64(iv + encrypted_data)
    end

    def decrypt(encrypted_data)
      # puts "Encrypted data before decoding: #{encrypted_data.inspect}"
      decipher = OpenSSL::Cipher.new(ALGORITHM)
      decipher.decrypt
      decipher.key = @key
      raw_data = Base64.strict_decode64(encrypted_data)
      decipher.iv = raw_data[0, decipher.iv_len]
      decipher.update(raw_data[decipher.iv_len..-1]) + decipher.final
    rescue OpenSSL::Cipher::CipherError => e
      puts "Decryption failed: #{e.message}"
      nil
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
kafkr-0.18.0 lib/kafkr/encryptor.rb
kafkr-0.13.0 lib/kafkr/encryptor.rb
kafkr-0.11.0 lib/kafkr/encryptor.rb
kafkr-0.10.0 lib/kafkr/encryptor.rb