Class: Pubnub::Crypto::LegacyCryptor
- Defined in:
- lib/pubnub/modules/crypto/cryptors/legacy_cryptor.rb
Overview
Legacy cryptor.
The cryptor provides encryption and decryption using `AES-256 in CBC mode with a cipher key and configurable initialization vector randomness. When it is registered as a secondary with other cryptors, it will provide backward compatibility with previously encrypted data.
Important: It has been reported that the digest from cipherKey has low entropy, and it is suggested to use AesCbcCryptor instead.
Constant Summary collapse
- BLOCK_SIZE =
AES-128 CBC block size.
16
Instance Method Summary collapse
- #decrypt(data) ⇒ Object
- #encrypt(data) ⇒ Object
- #identifier ⇒ Object
-
#initialize(cipher_key, use_random_iv = true) ⇒ LegacyCryptor
constructor
Create legacy cryptor instance.
Constructor Details
#initialize(cipher_key, use_random_iv = true) ⇒ LegacyCryptor
Create legacy cryptor instance.
22 23 24 25 26 27 28 |
# File 'lib/pubnub/modules/crypto/cryptors/legacy_cryptor.rb', line 22 def initialize(cipher_key, use_random_iv = true) @alg = 'AES-256-CBC' @original_cipher_key = cipher_key @cipher_key = Digest::SHA256.hexdigest(cipher_key.to_s).slice(0, 32) @iv = use_random_iv ? nil : '0123456789012345' super() end |
Instance Method Details
#decrypt(data) ⇒ Object
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
# File 'lib/pubnub/modules/crypto/cryptors/legacy_cryptor.rb', line 55 def decrypt(data) encrypted_data = data.data iv = if @iv.nil? && encrypted_data.length >= BLOCK_SIZE encrypted_data.slice!(0..(BLOCK_SIZE - 1)) if encrypted_data.length >= BLOCK_SIZE else @iv end if iv.length != BLOCK_SIZE puts "Pubnub :: DECRYPTION ERROR: Unexpected initialization vector length: #{data.metadata.length} bytes (#{BLOCK_SIZE} bytes is expected)" return nil end unless encrypted_data.length.positive? puts 'Pubnub :: DECRYPTION ERROR: Empty data for decryption' return nil end cipher = OpenSSL::Cipher.new(@alg).decrypt cipher.key = @cipher_key cipher.iv = iv decrypted = cipher.update encrypted_data decrypted << cipher.final rescue StandardError => e puts "Pubnub :: DECRYPTION ERROR: #{e}" nil end |
#encrypt(data) ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/pubnub/modules/crypto/cryptors/legacy_cryptor.rb', line 34 def encrypt(data) if data.nil? || data.empty? puts 'Pubnub :: ENCRYPTION ERROR: Empty data for encryption' return nil end iv = @iv || OpenSSL::Random.random_bytes(BLOCK_SIZE) cipher = OpenSSL::Cipher.new(@alg).encrypt cipher.key = @cipher_key cipher.iv = iv = '' << iv if @iv.nil? && iv << cipher.update(data) << cipher.final Crypto::EncryptedData.new() rescue StandardError => e puts "Pubnub :: ENCRYPTION ERROR: #{e}" nil end |
#identifier ⇒ Object
30 31 32 |
# File 'lib/pubnub/modules/crypto/cryptors/legacy_cryptor.rb', line 30 def identifier '\x00\x00\x00\x00' end |