Class: Pubnub::Crypto::AesCbcCryptor

Inherits:
Cryptor show all
Defined in:
lib/pubnub/modules/crypto/cryptors/aes_cbc_cryptor.rb

Overview

AES-256-CBC cryptor.

The cryptor provides encryption and decryption using AES-256 in CBC mode with a cipher key and random initialization vector. When it is registered as a secondary with other cryptors, it will provide backward compatibility with previously encrypted data.

Constant Summary collapse

BLOCK_SIZE =

AES-128 CBC block size.

16

Instance Method Summary collapse

Constructor Details

#initialize(cipher_key) ⇒ AesCbcCryptor

Create AES-256-CBC cryptor instance.

Parameters:

  • cipher_key (String)

    Key for data encryption and decryption.



19
20
21
22
23
# File 'lib/pubnub/modules/crypto/cryptors/aes_cbc_cryptor.rb', line 19

def initialize(cipher_key)
  @cipher_key = Digest::SHA256.digest(cipher_key)
  @alg = 'AES-256-CBC'
  super()
end

Instance Method Details

#decrypt(data) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/pubnub/modules/crypto/cryptors/aes_cbc_cryptor.rb', line 48

def decrypt(data)
  if data..length != BLOCK_SIZE
    puts "Pubnub :: DECRYPTION ERROR: Unexpected initialization vector length:
#{data..length} bytes (#{BLOCK_SIZE} bytes is expected)"
    return nil
  end

  cipher = OpenSSL::Cipher.new(@alg).decrypt
  cipher.key = @cipher_key
  cipher.iv = data.

  decrypted = cipher.update data.data
  decrypted << cipher.final
rescue StandardError => e
  puts "Pubnub :: DECRYPTION ERROR: #{e}"
  nil
end

#encrypt(data) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/pubnub/modules/crypto/cryptors/aes_cbc_cryptor.rb', line 29

def encrypt(data)
  if data.nil? || data.empty?
    puts 'Pubnub :: ENCRYPTION ERROR: Empty data for encryption'
    return nil
  end

  iv = OpenSSL::Random.random_bytes BLOCK_SIZE
  cipher = OpenSSL::Cipher.new(@alg).encrypt
  cipher.key = @cipher_key
  cipher.iv = iv

  encoded_message = cipher.update data
  encoded_message << cipher.final
  Crypto::EncryptedData.new(encoded_message, iv)
rescue StandardError => e
  puts "Pubnub :: ENCRYPTION ERROR: #{e}"
  nil
end

#identifierObject



25
26
27
# File 'lib/pubnub/modules/crypto/cryptors/aes_cbc_cryptor.rb', line 25

def identifier
  'ACRH'
end