#![allow(warnings)]
use wechat_work_crypto::WXBizMsgCrypt;
fn main() {
const TOKEN: &str = "QDG6eK";
const ENCODING_AES_KEY: &str = "AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA";
const RECEIVE_ID: &str = "wx5823bf96d3bd56c7";
let crypt = WXBizMsgCrypt::new(TOKEN, ENCODING_AES_KEY, RECEIVE_ID)
.expect("Failed to create WXBizMsgCrypt instance");
println!("=== WeChat Crypto Library Demo ===\n");
println!("Example 1: Verify URL");
let test_message = "hello from verify_url test";
let timestamp = "1409659813";
let nonce = "263014780";
match crypt.encrypt_msg(test_message, timestamp, nonce) {
Ok(encrypted_xml) => {
println!(" Generated encrypted message for verification...");
let encrypt_msg = wechat_work_crypto::WXBizMsgCrypt::get_xml_field(&encrypted_xml, "Encrypt").unwrap();
let msg_signature = wechat_work_crypto::WXBizMsgCrypt::get_xml_field(&encrypted_xml, "MsgSignature").unwrap();
match crypt.verify_url(&msg_signature, timestamp, nonce, &encrypt_msg) {
Ok(echo_result) => {
println!("✓ URL verification successful!");
println!(" Original message: {}", test_message);
println!(" Verified message: {}", echo_result);
if echo_result == test_message {
println!(" ✓ Verification matches original message!");
} else {
println!(" ✗ Verification doesn't match!");
}
}
Err(e) => {
println!("✗ URL verification failed: {} (error code: {})", e, e.error_code());
}
}
}
Err(e) => {
println!("✗ Failed to generate test data: {} (error code: {})", e, e.error_code());
}
}
println!();
println!("Example 2: Encrypt message");
let reply_msg = r#"<xml>
<ToUserName><![CDATA[openID]]></ToUserName>
<FromUserName><![CDATA[gh_123456789]]></FromUserName>
<CreateTime>1409659813</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[Hello from Rust!]]></Content>
</xml>"#;
let encrypt_timestamp = "1409659813";
let encrypt_nonce = "263014780";
match crypt.encrypt_msg(reply_msg, encrypt_timestamp, encrypt_nonce) {
Ok(encrypted_xml) => {
println!("✓ Message encrypted successfully!");
println!(" Encrypted XML:\n{}", encrypted_xml);
println!("\nExample 3: Decrypt message");
let post_data = &encrypted_xml;
match wechat_work_crypto::WXBizMsgCrypt::get_xml_field(post_data, "MsgSignature") {
Ok(signature) => {
match crypt.decrypt_msg(&signature, encrypt_timestamp, encrypt_nonce, post_data) {
Ok(decrypted_msg) => {
println!("✓ Message decrypted successfully!");
println!(" Decrypted message:\n{}", decrypted_msg);
if decrypted_msg == reply_msg {
println!(" ✓ Round-trip verification passed!");
} else {
println!(" ✗ Round-trip verification failed!");
}
}
Err(e) => {
println!("✗ Decryption failed: {} (error code: {})", e, e.error_code());
}
}
}
Err(e) => {
println!("✗ Failed to extract signature: {}", e);
}
}
}
Err(e) => {
println!("✗ Encryption failed: {} (error code: {})", e, e.error_code());
}
}
println!("\n=== Demo completed ===");
}