How to use sample code to access encryption and decryption and technical solutions

How to use sample code to access encryption and decryption and technical solutions

How to use sample code to access encryption and decryption, refer to this document and use the sample code, the access of encryption and decryption will be very simple. For further details, please check the technical solution. WeChat public platform provides sample codes in 5 languages: C++, PHP, Java, Python and C#. The class name and interface name of each language are the same. The following takes C++ as an example:

Function Description

Constructor

  1. // @param sToken: Token set by the developer on the public platform  
  2. // @param sEncodingAESKey: EncodingAESKey set by the developer on the public platform  
  3. // @param sAppid: appid of the public account  
  4. WXBizMsgCrypt( const std::string &sToken,
  5. const std::string &sEncodingAESKey,
  6. const std::string &sAppid);

Decryption function

  1. // Verify the authenticity of the message and obtain the decrypted plaintext  
  2. // @param sMsgSignature: signature string, corresponding to the msg_signature of the URL parameter  
  3. // @param sTimeStamp: timestamp, corresponding to the timestamp of the URL parameter  
  4. // @param sNonce: random string, corresponding to the nonce of the URL parameter  
  5. // @param sPostData: ciphertext, corresponding to the data of the POST request  
  6. // @param sMsg: decrypted plaintext, valid when return returns 0  
  7. // @return: 0 if successful, or the corresponding error code if failed  
  8. int DecryptMsg( const std::string &sMsgSignature,
  9. const std::string &sTimeStamp,
  10. const std::string &sNonce,
  11. const std::string &sPostData,
  12. std::string &sMsg);

Encryption Function

  1. //Encrypt and package the public account's reply message to the user  
  2. // @param sReplyMsg: the message to be replied to by the public account, a string in XML format  
  3. // @param sTimeStamp: timestamp, you can generate it yourself or use the timestamp of the URL parameter  
  4. // @param sNonce: random string, you can generate it yourself or use the nonce of the URL parameter  
  5. // @param sEncryptMsg: The encrypted ciphertext can be directly replied to the user, including msg_signature, timestamp, nonce, encrypted XML format string, valid when return returns 0  
  6. // return: 0 on success, corresponding error code on failure  
  7. int EncryptMsg( const std::string &sReplyMsg,
  8. const std::string &sTimeStamp,
  9. const std::string &sNonce,
  10. std::string &sEncryptMsg);

How to use

In safe mode or compatible mode, two new parameters encrypt_type and msg_signature will be added to the URL. encrypt_type indicates the encryption type, and msg_signature indicates the signature of the message body. If there is no encrypt_type parameter on the URL or its value is raw, it means no encryption; when encrypt_type is aes, it means aes encryption (currently there are only two values, raw and aes). Public account developers use this parameter to determine whether the messages sent by the WeChat public platform are encrypted.

The encryption and decryption methods in compatible mode and secure mode are exactly the same. The XML message body in compatible mode has several more plaintext fields than that in secure mode. For details, please refer to the "Detailed Technical Solution for Message Encryption and Decryption".

Instantiating an object

Use the constructor to instantiate an object and pass in the public account's token, appid, and EncodingAESKey.

Decryption

In security mode or compatible mode, the official account receives the following encrypted message body (“…” indicates the plaintext field in compatible mode):

  1. encrypt_msg =
  2. <xml>
  3. <ToUserName><![CDATA[gh_10f6c3c3ac5a]]></ToUserName>
  4. <Encrypt><![CDATA[hQM/NS0ujPGbF+/8yVe61E3mUVWVO1izRlZdyv26zrVUSE3zUEBdcXITxjbjiHH38kexVdpQLCnRfbrqny1yGvgqqKTGKxJWWQ9D5WiiUKx avHRNzYVzAjYkp7esNGy7HJcl/P3BGarQF3+AWyNQ5w7xax5GbOwiXD54yri7xmNMHBOHapDzBslbnTFiEy+8sjSl4asNbn2+ZVBpqGsyKDv0ZG+DlSlXlW+gNPVLP +YxeUhJcyfp91qoa0FJagRNlkNul4mGz+sZXJs0WF7lPx6lslDGW3J66crvIIx/klpl0oa/tC6n/9c8OFQ9pp8hrLq7B9EaAGFlIyz5UhVLiWPN97JkL6JCfxVooVM EKcKRrrlRDGe8RWVM3EW/nxk9Ic37lYY5j97YZfq375AoTBdGDtoPFZsvv3Upyut1i6G0JRogUsMPlyZl9B8Pl/wcA7k7i4LYMr2yK4SxNFrBUw==]]></Encrypt>
  5. </xml>

Call the DecryptMsg interface and pass in the parameters received on the URL: msg_signature (note: not signature, but msg_signature), timestamp, nonce and the received encrypt_msg. If the call is successful, sMsg is the output result, and its content is the following plain text xml message body:

  1. <xml>
  2. <ToUserName><![CDATA[gh_10f6c3c3ac5a]]></ToUserName>
  3. <FromUserName><![CDATA[oyORnuP8q7ou2gfYjqLzSIWZf0rs]]></FromUserName>
  4. <CreateTime>1411035097</CreateTime>
  5. <MsgType><![CDATA[text]]></MsgType>
  6. <Content><![CDATA[ this is a test message]]></Content>
  7. <MsgId>6060349595123187712</MsgId>
  8. </xml>

#p#

Public account processing message

Generate the XML message body that needs to be replied to the WeChat public platform. Assume that the reply contains the following content:

  1. res_msg =
  2. <xml>
  3. <ToUserName><![CDATA[oyORnuP8q7ou2gfYjqLzSIWZf0rs]]></ToUserName>
  4. <FromUserName><![CDATA[gh_10f6c3c3ac5a]]></FromUserName>
  5. <CreateTime>1411034505</CreateTime>
  6. <MsgType><![CDATA[text]]></MsgType>
  7. <Content><![CDATA[Welcome to join us!]]></Content>
  8. <FuncFlag>0</FuncFlag>
  9. </xml>

Packet encryption

Call the EncryptMsg interface and pass in the res_msg, timestamp, and nonce that need to be replied to the WeChat public platform. If the encryption is successful, sEncryptMsg is the ciphertext message body, and the content is as follows:

  1. <xml>
  2. <Encrypt><![CDATA[LDFAmKFr7U/RMmwRbsR676wjym90byw7+hhh226e8bu6KVYy00HheIsVER4eMgz/VBtofSaeXXQB z6fVdkN2CzBUaTtjJeTCXEIDfTBNxpw/QRLGLqqMZHA3I+JiBxrrSzd2yXuXst7TdkVgY4lZEHQcWk85x1niT79XLaWQog+ OnBV31eZbXGPPv8dZciKqGo0meTYi+fkMEJdyS8OE7NjO79vpIyIw7hMBtEXPBK/tJGN5m5SoAS6I4rRZ8Zl8umKxXqgr7N 8ZOs6DB9tokpvSl9wT9T3E62rufaKP5EL1imJUd1pngxy09EP24O8Th4bCrdUcZpJio2l11vE6bWK2s5WrLuO0cKY2GP2un Q4fDxh0L4ePmNOVFJwp9Hyvd0BAsleXA4jWeOMw5nH3Vn49/Q/ZAQ2HN3dB0bMA+6KJYLvIzTz/Iz6vEjk8ZkK+AbhW5eld nyRDXP/OWfZH2P3WQZUwc/G/LGmS3ekqMwQThhS2Eg5t4yHv0mAIei07Lknip8nnwgEeF4R9hOGutE9ETsGG4CP1LHTQ4fg YchOMfB3wANOjIt9xendbhHbu51Z4OKnA0F+MlgZomiqweT1v/+LUxcsFAZ1J+Vtt0FQXElDKg+YyQnRCiLl3I+GJ/cxSj8 6XwClZC3NNhAkVU11SvxcXEYh9smckV/qRP2Acsvdls0UqZVWnPtzgx8hc8QBZaeH+JeiaPQD88frNvA==]]></Encrypt>
  3. <MsgSignature><![CDATA[8d9521e63f84b2cd2e0daa124eb7eb0c34b6204a]]></MsgSignature>
  4. <TimeStamp>1411034505</TimeStamp>
  5. <Nonce><![CDATA[1351554359]]></Nonce>
  6. </xml>

Precautions

The length of EncodingAESKey is fixed to 43 characters, selected from az, AZ, 0-9, a total of 62 characters. The public account can be modified in the server configuration of the developer center of the public platform

For security reasons, the public platform website provides the function of modifying the EncodingAESKey (modify when the EncodingAESKey may be leaked), so it is recommended that the public account save the current and last EncodingAESKey. If the current EncodingAESKey fails to decrypt, try to use the last EncodingAESKey to decrypt. When replying, the key that successfully decrypts is used to encrypt the corresponding reply.

In compatible mode, the message body contains both plain text and cipher text. The message body will increase to about 3 times the previous size. Developers should check the system to prevent reception errors caused by longer messages and increased URL parameters.

If there is no encrypt_type parameter on the URL or its value is raw, then the reply is in plain text, otherwise it is in cipher text. During the compatible mode, the public account can reply in plain text or cipher text (do not reply in both types)

Function error return code

#p#

Download sample code

WeChat public platform provides developers with sample codes in 5 languages ​​(including C++, PHP, Java, Python and C# versions) Click to download../static/assets/a5a22f38cb60228cb32ab61d9e4c414b.zip

WeChat public platform interface debugging tool

Click to enter http://mp.weixin.qq.com/debug

Technical Solution

1. The length of EncodingAESKey is fixed at 43 characters, selected from az, AZ, 0-9, a total of 62 characters. The public account can be modified in the server configuration of the developer center of the public platform;

2. AES key: AESKey = Base64_Decode (EncodingAESKey + "="), the end of EncodingAESKey is padded with a character "=", and Base64_Decode is used to generate a 32-byte AESKey;

3. AES uses CBC mode, the key length is 32 bytes, and the data is padded with PKCS#7; PKCS#7: K is the number of key bytes (32), buf is the content to be encrypted, and N is the number of bytes. Buf needs to be padded to an integer multiple of K. (KN%K) bytes are padded at the end of buf, and the content of each byte is (K- N%K);

For details, see: http://tools.ietf.org/html/rfc2315

5. For security reasons, the public platform website provides the function of modifying EncodingAESKey (modify when EncodingAESKey may be leaked), so it is recommended that the public account save the current and previous EncodingAESKey. If the AESKey generated by the current EncodingAESKey fails to decrypt, try to use the previous AESKey to decrypt. When replying, the AESKey that successfully decrypts is used to encrypt the corresponding reply;

6. In compatible mode, the message body contains both plain text and cipher text, and the message body will increase to about 3 times as much as before. Developers should check the system to prevent reception errors caused by longer messages and increased URL parameters.

7. The WeChat team provides sample codes in multiple languages ​​(including PHP, Java, C++, Python, and C#). Please use the sample codes as much as possible. (../static/assets/a5a22f38cb60228cb32ab61d9e4c414b.zip)

The following takes ordinary text messages as an example to explain in detail the method and process of encrypting and decrypting the message body on the public platform. The encryption and decryption of other ordinary messages and event messages can be deduced in the same way.

Public accounts receive user messages

Message body encryption

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

  1. msg =
  2. <xml>
  3. <ToUserName><![CDATA[toUser]]></ToUserName>
  4. <FromUserName><![CDATA[fromUser]]></FromUserName>
  5. <CreateTime>1348831860</CreateTime>
  6. <MsgType><![CDATA[text]]></MsgType>
  7. <Content><![CDATA[ this is a test]]></Content>
  8. <MsgId>1234567890123456</MsgId>
  9. </xml>

During compatible mode, both plaintext and ciphertext are preserved, and the message format is as follows:

  1. new_msg=
  2. <xml>
  3. <ToUserName><![CDATA[toUser]]></ToUserName>
  4. <FromUserName><![CDATA[fromUser]]></FromUserName>
  5. <CreateTime>1348831860</CreateTime>
  6. <MsgType><![CDATA[text]]></MsgType>
  7. <Content><![CDATA[ this is a test]]></Content>
  8. <MsgId>1234567890123456</MsgId>
  9. <Encrypt><![CDATA[msg_encrypt]]</Encrypt>
  10. </xml>

In secure mode, the message body contains only ciphertext in the following format:

  1. new_msg=
  2. <xml>
  3. <ToUserName><![CDATA[toUser]]</ToUserName>
  4. <Encrypt><![CDATA[msg_encrypt]]</Encrypt>
  5. </xml>
  6.  
  7. Among them, msg_encrypt = Base64_Encode(AES_Encrypt[random(16B) + msg_len(4B) + msg + $AppId] )

The AES-encrypted buf consists of a 16-byte random string, a 4-byte msg_len (network byte order), msg, and $AppId, where msg_len is the length of msg and $AppId is the AppId of the public account.

AESKey = Base64_Decode(EncodingAESKey + "="), 32 bytes

Add the parameter encrypt_type to the URL. When the value of encrypt_type is raw, it means no encryption. When the value of encrypt_type is aes, it means aes encryption (currently there are only two values, raw and aes). No encrypt_type parameter also means no encryption

Message body signature

In order to verify the legitimacy of the message body, the public platform adds a message body signature, which developers can use to verify the authenticity of the message body and decrypt the verified message body.

Add parameter to the url: msg_signature

msg_signature=sha1(sort(Token, timestamp, nonce, msg_encrypt))

Message body verification and decryption

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

Verification

1. The developer calculates the signature, dev_msg_signature=sha1(sort(Token, timestamp, nonce, msg_encrypt))

2. Compare dev_msg_signature and msg_signature on the URL to see if they are equal. If they are equal, verification is successful.

The decryption method is as follows:

  1. 1. aes_msg=Base64_Decode(msg_encrypt)
  2.  
  3. 2. rand_msg=AES_Decrypt(aes_msg)
  4.  
  5. 3. Verify whether the $AppId at the end is your own AppId. If they are the same, it means the message has not been tampered with. This further strengthens the message signature verification.
  6.  
  7. 4. Remove the 16 random bytes in the rand_msg header, the 4 bytes of msg_len, and the $AppId at the end to get the final XML message body.

The public account replies to the user

If there is no encrypt_type in the URL or its value is raw, then the reply is in plain text, otherwise it is encrypted according to the above encryption algorithm. During the compatible mode, the public account can reply in plain text or cipher text (do not reply in both types)

Signature and encryption of reply message body

Existing message formats:

  1. msg =
  2. < xml >  
  3. < ToUserName > <![CDATA[toUser]]> </ ToUserName >  
  4. < FromUserName > <![CDATA[fromUser]]> </ FromUserName >  
  5. <CreateTime> 12345678 </CreateTime>  
  6. < MsgType > <![CDATA[text]]> </ MsgType >  
  7. < Content > <![CDATA[Hello]]> </ Content >  
  8. </ xml >  

Encrypted message format:

  1. new_msg =
  2. < xml >  
  3. < Encrypt > <![CDATA[msg_encrypt]]> </ Encrypt >  
  4. < MsgSignature > <![CDATA[msg_signature]]> </ MsgSignature >  
  5. <TimeStamp> timestamp </TimeStamp>  
  6. < Nonce > <![CDATA[nonce]]> </ Nonce >  
  7. </ xml >   

Among them, msg_encrypt=Base64_Encode(AES_Encrypt [random(16B)+ msg_len(4B) + msg + $AppId])

random(16B) is a 16-byte random string; msg_len is the length of msg, which occupies 4 bytes (network byte order); $AppId is the AppId of the public account

AESKey = Base64_Decode(EncodingAESKey + "="), 32 bytes

msg_signature=sha1(sort(Token, timestamp, nonce, msg_encrypt))

Timestamp and nonce can be filled back with the value in the request or regenerated

<<:  Overview of the public platform message body signature and encryption and decryption solution

>>:  Message signing and encryption/decryption - Developer Q&A

Recommend

Detailed explanation of Tik Tok information flow delivery strategy!

Nowadays, more and more companies and projects ar...

Apple's App Store policy changes are not painful: they do not affect the core

Beijing time, August 30 morning news, according t...

Gree Electric and Dong Mingzhu usher in new leadership

Fame brings gossip. As a hot-selling entrepreneur...

Have you paid attention to these "bullshit" things?

Whether at home, in the elevator, on the subway, ...

Cooperative SEO training: Why can’t I rank high after doing so much?

When we do website optimization, we must combine ...

How to do ASO optimization (Must read for App operation and promotion)

Share outline: 1. ASO optimization 2. How to do b...

Why Sony WH-H800 is the most worthwhile wireless headset to buy in 2017?

How to choose a suitable headset for the new smar...