Sha256: d8c3fd3ff338b2cdb2e9147c3383c2ed437c7f1651723a5e4d13f503b4aa07c2

Contents?: true

Size: 939 Bytes

Versions: 4

Compression:

Stored size: 939 Bytes

Contents

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

module Keen
  module AESHelper

    BLOCK_SIZE = 32

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

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

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

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

    def pad(msg)
      pad_len = BLOCK_SIZE - (msg.length % BLOCK_SIZE)
      padding = pad_len.chr * pad_len
      padded = msg + padding
      padded
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
keen-0.9.4 lib/keen/aes_helper.rb
keen-0.9.3 lib/keen/aes_helper.rb
keen-0.9.2 lib/keen/aes_helper.rb
keen-0.9.1 lib/keen/aes_helper.rb