Class: Kafkr::Encryptor

Inherits:
Object
  • Object
show all
Defined in:
lib/kafkr/encryptor.rb

Constant Summary collapse

ALGORITHM =
"aes-256-cbc"

Instance Method Summary collapse

Constructor Details

#initializeEncryptor

Returns a new instance of Encryptor.



8
9
10
# File 'lib/kafkr/encryptor.rb', line 8

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

Instance Method Details

#decrypt(encrypted_data) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/kafkr/encryptor.rb', line 21

def decrypt(encrypted_data)
  # Kafkr.log "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
  Kafkr.log "Decryption failed: #{e.message}"
  nil
end

#encrypt(data) ⇒ Object



12
13
14
15
16
17
18
19
# File 'lib/kafkr/encryptor.rb', line 12

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