Class: WeixinMessageEncryptor

Inherits:
Object
  • Object
show all
Defined in:
lib/weixin_message_encryptor.rb,
lib/weixin_message_encryptor/version.rb

Constant Summary collapse

BLOCK_SIZE =
32
VERSION =
'0.1.0.1'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(encoding_aes_key: nil, sign_token: nil, app_id: nil) ⇒ WeixinMessageEncryptor

Returns a new instance of WeixinMessageEncryptor.



13
14
15
16
17
# File 'lib/weixin_message_encryptor.rb', line 13

def initialize(encoding_aes_key: nil, sign_token: nil, app_id: nil)
  @encoding_aes_key = encoding_aes_key
  @sign_token = sign_token
  @app_id = app_id
end

Instance Attribute Details

#app_idObject (readonly)

Returns the value of attribute app_id.



11
12
13
# File 'lib/weixin_message_encryptor.rb', line 11

def app_id
  @app_id
end

#encoding_aes_keyObject (readonly)

Returns the value of attribute encoding_aes_key.



11
12
13
# File 'lib/weixin_message_encryptor.rb', line 11

def encoding_aes_key
  @encoding_aes_key
end

#sign_tokenObject (readonly)

Returns the value of attribute sign_token.



11
12
13
# File 'lib/weixin_message_encryptor.rb', line 11

def sign_token
  @sign_token
end

Instance Method Details

#decrypt(payload) ⇒ Object



43
44
45
46
47
48
# File 'lib/weixin_message_encryptor.rb', line 43

def decrypt(payload)
  encrypted_payload = payload['echostr'] || payload['xml']['Encrypt']
  sign = generate_signature encrypted_payload, payload['timestamp'], payload['nonce']
  message, app_id = decrypt_payload encrypted_payload
  return message, app_id, sign
end

#encrypt(payload) ⇒ Object



19
20
21
# File 'lib/weixin_message_encryptor.rb', line 19

def encrypt(payload)
  aes_encrypt(payload).delete("\n")
end

#encrypt_to_xml(payload) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/weixin_message_encryptor.rb', line 31

def encrypt_to_xml(payload)
  encrypted_payload, timestamp, nonce, signature = encrypt_with_signature(payload)
  <<XML
<xml>
<Encrypt><![CDATA[#{encrypted_payload}]]></Encrypt>
<MsgSignature><![CDATA[#{signature}]]></MsgSignature>
<TimeStamp>#{timestamp}</TimeStamp>
<Nonce><![CDATA[#{nonce}]]></Nonce>
</xml>
XML
end

#encrypt_with_signature(payload) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/weixin_message_encryptor.rb', line 23

def encrypt_with_signature(payload)
  encrypted_payload = encrypt(payload)
  timestamp = Time.now.to_i.to_s
  nonce = SecureRandom.hex(8)
  signature = generate_signature(encrypted_payload, timestamp, nonce)
  return [encrypted_payload, timestamp, nonce, signature]
end