Sha256: 44aec5d865fdb3c0f01e10c83e1499c8defeea71df87d415c4e7d6968411f4bf

Contents?: true

Size: 1.39 KB

Versions: 11

Compression:

Stored size: 1.39 KB

Contents

# TODO that file isn't refactored yet!
module Pubnub
  class Crypto
    def initialize(cipher_key)
      $logger.debug('Pubnub'){'Initializing Crypto'}
      @alg = 'AES-256-CBC'
      sha256_key = Digest::SHA256.hexdigest(cipher_key)
      @key = sha256_key.slice(0,32)

      @iv = '0123456789012345'
      $logger.debug('Pubnub'){'Initialized Crypto'}
    end


    def encrypt(message)

      aes = OpenSSL::Cipher::Cipher.new(@alg)
      aes.encrypt
      aes.key = @key
      aes.iv = @iv

      json_message = message.to_json
      cipher = aes.update(json_message)
      cipher << aes.final

      Base64.strict_encode64(cipher)

    end

    def decrypt(cipher_text)
      $logger.debug('Pubnub'){"Decrypting: #{cipher_text}"}
      decode_cipher = OpenSSL::Cipher::Cipher.new(@alg)
      decode_cipher.decrypt
      decode_cipher.key = @key
      decode_cipher.iv = @iv

      plain_text = ''

      begin
        undecoded_text = Base64.decode64(cipher_text)
        plain_text = decode_cipher.update(undecoded_text)
        plain_text << decode_cipher.final
      rescue => e
        $logger.error('Pubnub'){'DECRYPTION ERROR'}
        plain_text = '"DECRYPTION ERROR"'
      end

      begin
        JSON.load(plain_text)
      rescue JSON::ParserError
        JSON.load("[#{plain_text}]")[0] # srsly ruby? srsly?
      end

      $logger.debug('Pubnub'){'Finished decrypting'}

      plain_text

    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
pubnub-3.7.0 lib/pubnub/crypto.rb
pubnub-3.6.10 lib/pubnub/crypto.rb
pubnub-3.6.9 lib/pubnub/crypto.rb
pubnub-3.6.7 lib/pubnub/crypto.rb
pubnub-3.5.14 lib/pubnub/crypto.rb
pubnub-3.5.12 lib/pubnub/crypto.rb
pubnub-3.5.8 lib/pubnub/crypto.rb
pubnub-3.5.7 lib/pubnub/crypto.rb
pubnub-3.5.6 lib/pubnub/crypto.rb
pubnub-3.5.5 lib/pubnub/crypto.rb
pubnub-3.5.3 lib/pubnub/crypto.rb