Class: Pandora::Cryptor

Inherits:
Object
  • Object
show all
Defined in:
lib/pandora/util/cryptor.rb

Overview

Blowfish encryptor/decryptor for the Pandora Tuner API

Ciphertext is round-tripped to and from ASCII-encoded hexadecimal characters.

Keys must be provided. Available at pan-do-ra-api.wikia.com/wiki/Json/5/partners

Instance Method Summary collapse

Constructor Details

#initialize(encryption_key, decryption_key) ⇒ Cryptor

Returns a new instance of Cryptor.



14
15
16
17
# File 'lib/pandora/util/cryptor.rb', line 14

def initialize(encryption_key, decryption_key)
  @encryptor = Crypt::Blowfish.new(encryption_key)
  @decryptor = Crypt::Blowfish.new(decryption_key)
end

Instance Method Details

#decrypt(str) ⇒ Object



28
29
30
31
32
33
34
35
# File 'lib/pandora/util/cryptor.rb', line 28

def decrypt(str)
  str.force_encoding(Encoding::BINARY).
    scan(/.{1,16}/).map do |block|              # Operate on 16 char chunks
    block = pad([block].pack('H*'), 8)          # Convert ASCII hex to raw data
    @decryptor.decrypt_block(block)             # Decrypt the data
  end.join('').
    sub(/^(.*?)[[:cntrl:]]*$/, '\1')            # Strip trailing junk
end

#encrypt(str) ⇒ Object



19
20
21
22
23
24
25
26
# File 'lib/pandora/util/cryptor.rb', line 19

def encrypt(str)
  str.force_encoding(Encoding::BINARY).
    scan(/.{1,8}/).map do |block|               # Operate on 8 char chunks
    block = pad(block, 8) if block.length < 8   # Pad to 8 chars if under
    @encryptor.encrypt_block(block).            # Encrypt the data
      unpack('H*').first                        # Convert to ASCII hex
  end.join('')
end

#inspectObject

Override inspect so it doesn’t include internal Blowfish P-array and S-boxes from the instance variables.



39
40
41
# File 'lib/pandora/util/cryptor.rb', line 39

def inspect
  to_s
end