Class: Pubnub::Crypto

Inherits:
Object show all
Defined in:
lib/pubnub/crypto.rb

Overview

Internal Crypto class used for message encryption and decryption

Instance Method Summary (collapse)

Constructor Details

- (Crypto) initialize(cipher_key)

Returns a new instance of Crypto



5
6
7
8
9
10
11
# File 'lib/pubnub/crypto.rb', line 5

def initialize(cipher_key)
  @alg = 'AES-256-CBC'
  sha256_key = Digest::SHA256.hexdigest(cipher_key)
  @key = sha256_key.slice(0, 32)

  @iv = '0123456789012345'
end

Instance Method Details

- (Object) decrypt(cipher_text)



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/pubnub/crypto.rb', line 26

def decrypt(cipher_text)
  decode_cipher = OpenSSL::Cipher::Cipher.new(@alg).decrypt
  decode_cipher.key = @key
  decode_cipher.iv  = @iv

  plain_text = decryption(cipher_text, decode_cipher)
  load_json(plain_text)

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

  plain_text
end

- (Object) encrypt(message)



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/pubnub/crypto.rb', line 13

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