# Summary

When the follower and the authorized Official Account message template/When the Mini Program interacts, the third-party platform will receive the corresponding message push and event push. Because third party platforms generally help numerous Official Account message template/Mini Program for business operations, so in order to strengthen security, the WeChat server will conduct this process 2 One measure:

  1. inReceive Authorized Official Account message template Messages and events of the URL In, increase 2 Parameters (previously 2 Parameters, timestamp Timestamp, random number Nonce), respectively, are encrypt_Type (encryption type, for Aes) and msg_Signature (message body signature, used to verify the correctness of the message body)
  2. postdata to hit the target XML Body, will use the encryption of the received message when the third party platform is applied symmetric_Key (also known as EncodingAESKey) for encryption.

# Encryption and decryption technology scheme

The message encryption and decryption scheme of open platform is based on [AES Encryption and decryption algorithm](http://zh.wikipedia.org/The wiki/%E9%AB%98%E7%BA%A7%E5%8A%A0%E5%AF%86%E6%A0%87%E5%87%86)To achieve, as follows:

  1. EncodingAESKey: Message encryption and decryption Key, the length is fixed to 43 One character, from a-z,A-Z,0-9 common 62 Selected in a character. Created by the developer. Official Account message template Plug-in when filling, can also apply for modification.

  2. AESKey: AESKey=Base64_Decode(EncodingAESKey + "="),EncodingAESKey The trailing padding of a character "=", use Base64_Decode generate 32 One byte AESKey

  3. AES Use CBC Mode, the secret key length is 32 Bytes (256 Bit), the data is adopted PKCS#7 Fill PKCS#7:K For the number of key bytes 32),Buf For the content to be encrypted, n Number of its bytes. Buf Needs to be filled with K An integer multiple of. in Buf The tail fill of the(K - N%K)The contents of each byte. yes(K - N%K)。

Tail fill Introductions Example
01 if ( N%K==(K-1))
0202 if ( N%K==(K-2))
030303 if ( N%K==(K-3))
... ...
KK....KK (K A byte) if ( N%K==0)

See details:http://tools.ietf.Org/html/rfc2315

  1. BASE64 Use MIME Format, characters including upper and lower case letters each 26 One, plus 10 Number and plus. "+," slash "/" , Total 64 Character, equal sign "=" Used as suffix fill

  2. For security reasons, the Open Platform Web site provides modifications EncodingAESKey The function (in the EncodingAESKey Modify when possible leakage, corresponding to the encryption of received messages filled in when applying on the third-party platform symmetric_Key), so it is recommended to open the platform account to save the current and last EncodingAESKey, if current EncodingAESKey Generated AESKey Decryption fails, an attempt is made with the last AESKey Of the decryption. When returning the package, which one to use AESKey Decryption is successful, use this AESKey Encrypt the corresponding return packet.

  3. The WeChat team provides sample code in multiple languages (including PHP, Java, C, Python, C#), please developers try to use the sample code, carefully read the technical documentation, sample code and comments, and then code debugging.<a url=http://wximg.gtimg.com/shake_tv/mpwiki/cryptoDemo.zip" target="_blank">Sample Download

# Receive user messages from the authorized party

Taking ordinary text messages as an example, the methods and processes of public platform encryption and decryption of message bodies are described in detail. Other ordinary messages and event messages can be encrypted and decrypted, and so on.

# Message body encryption

]LP - The existing message is in plain text and has the following format:

<xml>
  <ToUserName><![CDATA[Sample Content]]></ToUserName>
  <FromUserName><![CDATA[Sample Content]]></FromUserName>
  <CreateTime>1348831860</CreateTime>
  <MsgType><![CDATA[Sample Content]]></MsgType>
  <Content><![CDATA[Sample Content]]></Content>
  <MsgId>1234567890123456</MsgId>
</xml>

After encryption, the message format is as follows:

<xml>
  <ToUserName><![CDATA[toUser]]></ToUserName>
  <Encrypt><![CDATA[msg_encrypt]]></Encrypt>
</xml>

Among them, msg_Encrypt is the result of the message encrypted by the platform as follows:

  • AESKey = Base64_Decode(EncodingAESKey + "=")
  • FullStr = random(16B) + msg_len(4B) + msg + appid
  • msg_encrypt = Base64_Encode( AES_Encrypt( FullStr, AESKey ) )

# Message body signature

In order to verify the legitimacy of the message body, the open platform adds a signature of the message body, which developers can use to verify the authenticity of the message body and decrypt the verified message body. The specific approach is as follows: in the WeChat server to the Official Account message template When a plug-in pushes a message, it receives the message Add parameters to the URL (filled in at creation): msg_signature  msg_signature=sha1(sort(Token、timestamp、nonce, msg_encrypt))

parameter describe
Token Check the received message set by the server on the open platform of Wechat Token
timestamp URL On the original parameters, time stamp
nuncio URL On the original parameters, random number
msg_encrypt Previously described ciphertext message body

# Message body verification and decryption

The developer first verifies the correctness of the message body signature, and then decrypts the message body after verification.

# Verification Method:

1. Developer Computing Signature, dev_msg_signature=sha1(sort(Token、timestamp、nonce, msg_encrypt))

2. Compare dev_msg_Signature and msg with the URL_If the signature is equal, equality means validation passes.

# The decryption is as follows:


1. TmpMsg = Base64_Decode(msg_encrypt) 

2. FullStr = AES_Decrypt(TmpMsg, AESKey)  FullStr As mentioned earlier consists of 4 parts (random, msg_len, msg, supports)

3. Verify the appid of the tail Is it correct (optional)

4. Remove 16 bytes of random and 4 bytes of msg from the FullStr header_Len, and appid at the tail, that is, get the plaintext content

# IV. Example: The service party responds to the message to the user instead of the authorization

# Signature and Encryption of Reply Message Body

Existing message format:

<xml>
  <ToUserName></ToUserName>
  <FromUserName></FromUserName>
  <CreateTime>12345678</CreateTime>
  <MsgType></MsgType>
  <Content></Content>
</xml>

Post-encrypted message format:

<xml>
  <Encrypt></Encrypt>
  <MsgSignature></MsgSignature>
  <TimeStamp></TimeStamp>
  <Nuncio></Nuncio>
</xml>

Among them, msg_encrypt = Base64_Encode( AES_Encrypt( FullStr, AESKey ) )

  • FullStr = random(16B) + msg_len(4B) + msg + appid
  • AESKey = Base64_Decode(EncodingAESKey + "=")

FullStr In,

  • random(16B)for 16 Random character string of bytes
  • msg_len for msg Length, accounting for 4 A byte(Network byte order)
  • msg The content of the service provider's reply
  • appid Appid for the service side

In addition, msg_signature=sha1(sort(Token、timestamp、nonce, msg_encrypt)),timestamp、nonce Backfill the value in the request.

# Examples of common mistakes

Developers in the process of message encryption and decryption may encounter common error problems, finishing the reasons are as follows:

  1. xml Incorrect format: as written (s Lowercase and p and>Spaces in the middle)
  2. The Public Platform website provides modifications EncodingAESKey The function, the public account needs to save the current and last EncodingAESKey, if the current EncodingAESKey Decryption fails, an attempt is made with the last EncodingAESKey Decryption. When returning the package, which one to use Key Decryption is successful, use this Key Encrypt the corresponding return packet.
  3. java Requirement jdk 1.6 Above
  4. abnormal java.security.InvalidKeyException:illegal Key Size The solution: Download at the official website JCE Unlimited permissions policy fileJDK7 The download address of the

Unzip it after downloading, you can see local_policy.jar and US_export_policy.jar as well as Readme.txt, if you have installed JRE, combine the two jar File to% JRE_HOME%libsecurity Overwrite the original file under the directoryIf you have installed The JDK, will be two jar File to% JDK_HOME%jrelibsecurity Overwrite original file in directory