Sha256: 4fbfaa037d5c183ae8ed3b365501ae92d5ac30726906fa474668363515602c15

Contents?: true

Size: 907 Bytes

Versions: 3

Compression:

Stored size: 907 Bytes

Contents

require 'openssl'
require 'digest'
require 'base64'

module Keen
  class AESHelper

    class << self
      def aes256_decrypt(key, iv_plus_encrypted)
        aes = OpenSSL::Cipher::AES.new(256, :CBC)
        iv = iv_plus_encrypted[0, aes.key_len]
        encrypted = iv_plus_encrypted[aes.key_len, iv_plus_encrypted.length]
        aes.decrypt
        aes.key = unhexlify(key)
        aes.iv = unhexlify(iv)
        aes.update(unhexlify(encrypted)) + aes.final
      end

      def aes256_encrypt(key, plaintext, iv = nil)
        aes = OpenSSL::Cipher::AES.new(256, :CBC)
        aes.encrypt
        aes.key = unhexlify(key)
        aes.iv = iv unless iv.nil?
        iv ||= aes.random_iv
        hexlify(iv) + hexlify(aes.update(plaintext) + aes.final)
      end

      def hexlify(msg)
        msg.unpack('H*')[0]
      end

      def unhexlify(msg)
        [msg].pack('H*')
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
keen-0.9.7 lib/keen/aes_helper.rb
keen-0.9.6 lib/keen/aes_helper.rb
keen-0.9.5 lib/keen/aes_helper.rb