Class: WeWhisper::Whisper

Inherits:
Object
  • Object
show all
Includes:
Cipher
Defined in:
lib/we_whisper/whisper.rb

Constant Summary

Constants included from Cipher

Cipher::BLOCK_SIZE, Cipher::CIPHER

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Cipher

#cipher_decrypt, #cipher_encrypt, #pack, #unpack

Constructor Details

#initialize(appid, token, encoding_aes_key, opts = {}) ⇒ Whisper

Returns a new instance of Whisper.



17
18
19
20
21
22
23
24
25
26
# File 'lib/we_whisper/whisper.rb', line 17

def initialize(appid, token, encoding_aes_key, opts={})
  @options = {
    assert_signature: true,
    assert_appid: true
  }.merge(opts)

  @appid = appid
  @token = token
  @encoding_aes_key = encoding_aes_key
end

Instance Attribute Details

#appidObject (readonly)

Returns the value of attribute appid.



15
16
17
# File 'lib/we_whisper/whisper.rb', line 15

def appid
  @appid
end

#encoding_aes_keyObject (readonly)

Returns the value of attribute encoding_aes_key.



15
16
17
# File 'lib/we_whisper/whisper.rb', line 15

def encoding_aes_key
  @encoding_aes_key
end

#optionsObject (readonly)

Returns the value of attribute options.



15
16
17
# File 'lib/we_whisper/whisper.rb', line 15

def options
  @options
end

#tokenObject (readonly)

Returns the value of attribute token.



15
16
17
# File 'lib/we_whisper/whisper.rb', line 15

def token
  @token
end

Instance Method Details

#decrypt_message(message, nonce = "", timestamp = "") ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/we_whisper/whisper.rb', line 28

def decrypt_message(message, nonce="", timestamp="")
  # 1. Get the encrypted content from XML Message
  encrypted_text = Message.get_encrypted_content_from_message(message)

  # 2. If we need to validate signature, generate one from the encrypted text
  #    and check with the Signature in message
  if options[:assert_signature] && signature = Message.get_signature_from_messge(message)
    sign = Signature.sign(token, timestamp, nonce, encrypted_text)
    raise InvalidSignature if sign != signature
  end

  # 3. Decode and decrypt the encrypted text
  decrypted_message, decrypted_appid = \
    Cryptor.decrypt(encrypted_text, encoding_aes_key)

  if options[:assert_appid]
    raise AppIdNotMatch if decrypted_appid != appid
  end

  decrypted_message
end

#encrypt_message(message, nonce, timestamp) ⇒ Object



50
51
52
53
54
55
56
57
58
59
# File 'lib/we_whisper/whisper.rb', line 50

def encrypt_message(message, nonce, timestamp)
  # 1. Encrypt and encode the xml message
  encrypt = Cryptor.encrypt(message, appid, encoding_aes_key)

  # 2. Create signature
  sign = Signature.sign(token, timestamp, nonce, encrypt)

  # 3. Construct xml
  Message.to_xml(encrypt, sign, timestamp, nonce)
end