public async Task <string> Post(string signature, string timestamp, string nonce, string msg_signature) { // 取出消息内容 string content = string.Empty; using (Stream stream = HttpContext.Request.Body) { byte[] buffer = new byte[HttpContext.Request.ContentLength.Value]; await stream.ReadAsync(buffer, 0, buffer.Length); content = Encoding.UTF8.GetString(buffer); } // 解密得到消息明文 string xmlMsg = string.Empty;//消息 if (!string.IsNullOrWhiteSpace(msg_signature)) { WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, sEncodingAESKey, sAppID); int ret = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, content, ref xmlMsg); if (ret != 0) { Console.WriteLine("ERR: Decrypt fail, ret: " + ret); return(""); } } BaseMessage msg = MessageFactory.CreateMessage(xmlMsg); return(msg.ResText(msg.FromUserName)); }
public void EncryptRequestMsgTest() { var xml = @"<xml> <MsgType>Text</MsgType> <Content><![CDATA[123]]></Content> <bizmsgmenuid><![CDATA[]]></bizmsgmenuid> <MsgId>637058302725818000</MsgId> <Encrypt><![CDATA[]]></Encrypt> <ToUserName><![CDATA[ToUserNameValue]]></ToUserName> <FromUserName><![CDATA[FromUserName(OpenId)]]></FromUserName> <CreateTime>1570204886</CreateTime> </xml>"; var token = "weixin"; var encodingAESKey = "YTJkZmVjMzQ5NDU5NDY3MDhiZWI0NTdiMjFiY2I5MmU"; var appId = "wx669ef95216eef885"; var timeStamp = SystemTime.NowTicks.ToString(); var nonce = (SystemTime.NowTicks * 2).ToString(); WXBizMsgCrypt msgCrype = new WXBizMsgCrypt(token, encodingAESKey, appId); var toUserName = "******"; string finalResponseXml = null, msgSigature = null; var ret = msgCrype.EncryptRequestMsg(xml, timeStamp, nonce, toUserName, ref finalResponseXml, ref msgSigature); Assert.AreEqual(0, ret); Console.WriteLine(finalResponseXml); Console.WriteLine(msgSigature); Console.WriteLine(); //进行解密 string decryptXml = null; ret = msgCrype.DecryptMsg(msgSigature, timeStamp, nonce, finalResponseXml, ref decryptXml); Assert.AreEqual(0, ret); Console.WriteLine(decryptXml); }
/// <summary> /// 获取微信发送过来的数据包。并处理加解密问题。如果进行了加密,则将密文解密后返回,否则直接返回接收到的字符 /// </summary> /// <param name="param">加解密接入参数</param> /// <returns>如果进行了加密,则将密文解密后返回,否则直接返回接收到的字符</returns> public static string GetRequestData(EnterParam param) { //获取当前请求的原始数据包 var reqdata = GetRequestData(); var timestamp = HttpContext.Current.Request.QueryString["timestamp"]; var nonce = HttpContext.Current.Request.QueryString["nonce"]; var msg_signature = HttpContext.Current.Request.QueryString["msg_signature"]; var encrypt_type = HttpContext.Current.Request.QueryString["encrypt_type"]; string postStr = null; if (encrypt_type == "aes") { //如果进行了加密,则加密成功后,直接发挥解密后的明文。解密失败则返回null param.IsAes = true; var ret = new WXBizMsgCrypt(param.token, param.EncodingAESKey, param.appid); if (ret.DecryptMsg(msg_signature, timestamp, nonce, reqdata, ref postStr) != 0) { return(null); } return(postStr); } else { param.IsAes = false; return(reqdata); } }
public string VerifyUrl(string id, string msg_signature, string timestamp, string nonce, string echostr) { if (!string.IsNullOrEmpty(id)) { var _config = this.GetConfig(id); string token = _config.Token; string aeskey = _config.EncodingAESKey; string corpid = _config.CropId; WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, aeskey, corpid); int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr, ref sEchoStr); if (ret != 0) { return(ret.ToString()); } else { return(sEchoStr); } } else { return(""); } }
/// <summary> /// 调用。 /// </summary> /// <param name="context">处理上下文。</param> /// <returns>任务。</returns> public override Task Invoke(IHandlerContext context) { var dependencyResolver = context.GetDependencyResolver(); var requestMessageFactory = dependencyResolver.GetService <IRequestMessageFactory>(); var content = context.Content; var parameters = context.GetRequestParameters(); #region Decrypt if (parameters.ContainsKey("encrypt_type")) { var nonce = parameters["nonce"]; var signature = parameters["msg_signature"]; var timestamp = parameters["timestamp"]; var baseInfo = context.GetMessageHandlerBaseInfo(); var appId = baseInfo.AppId; var encodingAesKey = baseInfo.EncodingAesKey; var token = baseInfo.Token; var wxBizMsgCrypt = new WXBizMsgCrypt(token, encodingAesKey, appId); wxBizMsgCrypt.DecryptMsg(signature, timestamp, nonce, content, ref content); } #endregion Decrypt context.SetRequestMessage(requestMessageFactory.CreateRequestMessage(content)); return(Next.Invoke(context)); }
string sEncodingAESKey = "h5f4q8lH72Qelx3SOmEo6pdilMjWzciqDucNfjbGNVV"; // 应用秘钥 8 #endregion public ActionResult Index() { Logger.Write("进入回调页面:CallBack/Index"); if (Request.HttpMethod.ToLower() == "post") { wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); string sReqMsgSig = Request.QueryString["msg_signature"] == null ? "" : Request.QueryString["msg_signature"].ToString(); //微信加密签名 string sReqTimeStamp = Request.QueryString["timestamp"] == null ? "" : Request.QueryString["timestamp"].ToString(); //时间戳 string sReqNonce = Request.QueryString["nonce"] == null ? "" : Request.QueryString["nonce"].ToString(); //随机数 string sReechostr = Request.QueryString["echostr"] == null ? "" : Request.QueryString["echostr"].ToString(); //随机字符串 string copyRight = "{msg_signature:'" + sReqMsgSig + "',timestamp:'" + sReqTimeStamp + "',nonce:'" + sReqNonce + "',echostr:'" + sReechostr + "'}"; Marisfrolg.Public.CookieHelper.RemoveCookie("copyRight"); Marisfrolg.Public.CookieHelper.SetCookie("copyRight", copyRight); Logger.Write("msg_signature:" + sReqMsgSig + "|timestamp:" + sReqTimeStamp + "|nonce:" + sReqNonce + "|echostr:" + sReechostr); } else { string echostr = Valid(); ViewBag.Title = echostr; } return(View()); }
public void valid(HttpContext context) { string sVerifyMsgSig = context.Request.QueryString["msg_signature"];//企业号的 msg_signature string sVerifyTimeStamp = context.Request.QueryString["timestamp"]; string sVerifyNonce = context.Request.QueryString["nonce"]; string sVerifyEchoStr = context.Request.QueryString["echoStr"]; int ret = 0; // int ret1 = 0; string sEchoStr = ""; // string sEchoStr1 = ""; WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); // WXBizMsgCrypt wxcpt1 = new WXBizMsgCrypt(sToken1, sEncodingAESKey1, sCorpID1); ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr); if (ret != 0) { context.Response.Write("ERR: VerifyURL fail, ret: " + ret); return; } if (!string.IsNullOrEmpty(sEchoStr)) { context.Response.Write(sEchoStr); context.Response.Flush(); //推送echostr,通过验证} } }
/// <summary> /// 返回XML格式的响应消息 /// </summary> /// <param name="encryptType">消息加密类型</param> /// <returns>返回XML格式的响应消息</returns> public string ToXml(MessageEncryptTypeEnum encryptType) { int WXBizMsgCrypt_OK = 0; //得到未加密的XML响应消息 string xml = ToXml(); //如果需要加密,加密消息 if (encryptType == MessageEncryptTypeEnum.aes) { int timeStamp = MyWay.Areas.WeiXin.Models.Utility.ToWeixinTime(CreateTime); Random random = new Random(); string nonce = random.Next().ToString(); AccountInfo account = AccountInfoCollection.GetAccountInfo(FromUserName); if (account != null) { WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(account.Token, account.EncodingAESKey, account.AppId); string xmlEncrypt = ""; //加密消息 if (wxcpt.EncryptMsg(xml, timeStamp.ToString(), nonce, ref xmlEncrypt) == WXBizMsgCrypt_OK) { return(xmlEncrypt); } } } return(xml); }
static void Main(string[] args) { string sToken = "6GPQsoax9yeWXRmA4siFFeVyojAn3LY"; string sCorpID = "wwaaa6a2c1d43426a6"; string sEncodingAESKey = "jAV8dy8cM6BsAjiXsUsTZ4vpHbvKN58Q5LeVLTjgeHe"; WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); string sVerifyMsgSig = System.Web.HttpUtility.UrlDecode("HNYJRDpKj8Yq3wLw"); string sVerifyTimeStamp = System.Web.HttpUtility.UrlDecode("1524885497"); string sVerifyNonce = System.Web.HttpUtility.UrlDecode("c2b6ada60ed292cae21fab8d6c17da14a42f8c33"); string sVerifyEchoStr = System.Web.HttpUtility.UrlDecode("rhPpD8WyDZfAUQT%2F3Kr5b3EAApDfSncTowFNz06yB7HMGcFAwW%2BMk48U2eduOFLBJ2AW8uEuYBoANWl8LpInWA%3D%3D", Encoding.UTF8); int ret = 0; string sEchoStr = String.Empty; ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr); if (ret != 0) { System.Console.WriteLine("ERR: VerifyURL fail, ret: " + ret); Console.WriteLine(ret); Console.WriteLine(sEchoStr); Console.Read(); } else { Console.WriteLine(sEchoStr); Console.Read(); } }
public Task Get(string msg_signature, string timestamp, string nonce, string echostr) { _log.LogInformation("开始执行"); WeChatAuthInfo weChatAuthInfo = WeChatOperation.GetWeChatAuthInfo(EnumWeChatAppType.Food); WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(weChatAuthInfo.Token, weChatAuthInfo.EncodingAESKey, weChatAuthInfo.CorpId); string sVerifyMsgSig = HttpUtility.UrlDecode(msg_signature); //string sVerifyMsgSig = "5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3"; string sVerifyTimeStamp = HttpUtility.UrlDecode(timestamp); // string sVerifyTimeStamp = "1409659589"; string sVerifyNonce = HttpUtility.UrlDecode(nonce); //string sVerifyNonce = "263014780"; string sVerifyEchoStr = HttpUtility.UrlDecode(echostr); //string sVerifyEchoStr = "P9nAzCzyDtyTWESHep1vC5X9xho/qYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp+4RPcs8TgAE7OaBO+FZXvnaqQ=="; int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr); if (ret != 0) { _log.LogInformation(ret.ToString()); return(Task.CompletedTask); } _log.LogInformation(sEchoStr); Response.WriteAsync(sEchoStr); return(Task.CompletedTask); }
private XDocument Init(XDocument postDataDocument, ReceiveRequestData postModel) { //进行加密判断并处理 var postDataStr = postDataDocument.ToString(); XDocument decryptDoc = postDataDocument; if (postModel != null && postDataDocument.Root.Element("Encrypt") != null && !string.IsNullOrEmpty(postDataDocument.Root.Element("Encrypt").Value)) { //使用了加密 string sToken = wxconfig.ServerToken; //消息校验Token string sAppId = wxconfig.ServerAppID; //申请到的第三方平台APPID string sEncodingAesKey = wxconfig.ServerEncodingAESKey; //消息加解密Key WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAesKey, sAppId); string msgXml = null; var result = wxcpt.DecryptMsg(postModel.msg_signature, postModel.timestamp, postModel.nonce, postDataStr, ref msgXml); //判断result类型 if (result != 0) { Log4NetHelper.logText("Init", "未解密成功"); //验证没有通过,取消执行 return(null); } decryptDoc = XDocument.Parse(msgXml);//完成解密 } return(decryptDoc); }
/// <summary> /// 返回消息,包含解密、加密 /// </summary> /// <param name="encrypt_type">类型</param> /// <param name="timestamp"></param> /// <param name="nonce"></param> /// <param name="postString"></param> /// <returns></returns> public string ReturnMessage(string encrypt_type, string msg_signature, string timestamp, string nonce, string postString) { string resultStr = ""; if (wxcpt == null) wxcpt = new WXBizMsgCrypt(CommonData.WeixinToken, CommonData.EncodingAESKey, CommonData.AppID); int flag = 0; if (encrypt_type.ToLower() == "aes") { //解密 flag = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, postString, ref postString); if (flag != 0) throw new Exception("接收时解密消息发生错误,错误码为" + flag); //LogHelper.WriteInfo(string.Format("接收时解密后的消息为:{0}",postString)); //end 解密 } resultStr = ReturnMessage(postString); //LogHelper.WriteInfo(string.Format("ReturnMessage得到的消息为:{0}", resultStr)); if (encrypt_type.ToLower() == "aes") { //加密 //LogHelper.WriteInfo(string.Format("回复时加密前的消息为:{0}", resultStr)); flag = wxcpt.EncryptMsg(resultStr, timestamp, nonce, ref resultStr); if (flag != 0) throw new Exception("回复时加密消息发生错误,错误码为" + flag); //end 加密 } return resultStr; }
public string CommonInitialize(Stream inputStream, QyPostModel postModel) { _postModel = postModel as QyPostModel; //1、从Stream获取加密字符串 var postDataStr = GetEncryptPostDataString(inputStream); EncryptPostData = XLH.DeserializeXmlFromString <EncryptPostData>(postDataStr, Encoding.UTF8); //2、解密:获得明文字符串 WXBizMsgCrypt msgCrypt = new WXBizMsgCrypt(_postModel.Token, _postModel.EncodingAESKey, _postModel.CorpId); string msgXml = null; var result = msgCrypt.DecryptMsg(_postModel.Msg_Signature, _postModel.Timestamp, _postModel.Nonce, postDataStr, ref msgXml); //判断result类型 if (result != 0) { //验证没有通过,取消执行 CancelExcute = true; return(null); } //XmlDocument requestDocument = new XmlDocument(); //requestDocument.LoadXml(msgXml); //3、对解密后的字符串反序列化 RequestMessage = XLH.DeserializeXmlFromString <RequestMessage>(msgXml, Encoding.UTF8); return(msgXml); }
public string Get() { var msg_signature = Request.Query["msg_signature"]; var timestamp = Request.Query["timestamp"]; var nonce = Request.Query["nonce"]; var echostr = Request.Query["echostr"]; try { WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(Config["CommpanyInfo:UrlVerificationToken"], Config["CommpanyInfo:EncodingAESKey"], Config["CommpanyInfo:CorpID"]); int ret = 0; string sEchoStr = ""; ret = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr, ref sEchoStr); if (ret != 0) { System.Console.WriteLine("ERR: VerifyURL fail, ret: " + ret); return(""); } return(sEchoStr); } catch { throw; } }
public static bool Check(string signature, string timestamp, string nonce, string Token, string encodingAESKey) { var sign = ""; WXBizMsgCrypt.GenarateSinature(Token, timestamp, nonce, encodingAESKey, ref sign); return(sign.Equals(signature)); }
public HttpResponse Get([FromUri] UrldecodeModel model) { string sToken = "HON82gwUh3jIu"; string sCorpID = "wwaaa6a2c1d43426a6"; string sEncodingAESKey = "cBQP0uSzY26amPKGUjYMqoqsz7VHPU6HSOQkDGorVlM"; WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); string sVerifyMsgSig = HttpUtility.UrlDecode(model.msg_signature); string sVerifyTimeStamp = HttpUtility.UrlDecode(model.timestamp); string sVerifyNonce = HttpUtility.UrlDecode(model.nonce); string sVerifyEchoStr = HttpUtility.UrlDecode(model.echostr); int ret = 0; string sEchoStr = string.Empty; ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr); if (ret != 0) { System.Console.WriteLine("ERR: VerifyURL fail, ret: " + ret); } HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Write(sEchoStr); HttpContext.Current.Response.End(); return(HttpContext.Current.Response); }
/// <summary> /// 微信响应方法 /// </summary> /// <param name="request"></param> /// <returns></returns> public override string Response(BaseResponseMessage response, EnterParamEntity param) { var _Response = response as TextResponseMessage; StringBuilder result = new StringBuilder(); result.AppendFormat("<xml>"); result.AppendFormat("<ToUserName><![CDATA[{0}]]></ToUserName>", _Response.ToUserName); result.AppendFormat("<FromUserName><![CDATA[{0}]]></FromUserName>", _Response.FromUserName); result.AppendFormat("<CreateTime>{0}></CreateTime>", _Response.CreateTime); result.AppendFormat("<MsgType><![CDATA[{0}]]></MsgType>", _Response.MsgType); result.AppendFormat("<Content><![CDATA[{0}]]></Content>", _Response.Content); result.AppendFormat("</xml>"); LogHelper.WriteLog("【微信Response】响应消息明文:" + result.ToString(), LogMessageType.Info); if (param.IsAes) { string data = string.Empty; int encrypt = new WXBizMsgCrypt(param.token, param.EncodingAESKey, param.appid). EncryptMsg(result.ToString(), _Response.CreateTime.ToString(), param.nonce, ref data); result = new StringBuilder(data); if (encrypt != 0) { LogHelper.WriteLog("【微信响应文本消息】加密失败", LogMessageType.Error); } LogHelper.WriteLog("【微信Response】响应消息加密:" + data, LogMessageType.Info); } return(result.ToString()); }
/// <summary> /// 验证url地址 /// </summary> /// <param name="_crypt"></param> /// <param name="_context"></param> public void VerifyURL(WXBizMsgCrypt _crypt, HttpContext _context) { string msg_signature = _context.Request.QueryString["msg_signature"]; string timestamp = _context.Request.QueryString["timestamp"]; string nonce = _context.Request.QueryString["nonce"]; string echostr = _context.Request.QueryString["echostr"]; //判断这四个参数是否为空。 if (!string.IsNullOrEmpty(echostr) && !string.IsNullOrEmpty(msg_signature) && !string.IsNullOrEmpty(nonce)) { string sReplyEchoStr = string.Empty; int result = _crypt.VerifyURL(msg_signature, timestamp, nonce, echostr, ref sReplyEchoStr); if (result == 0) { //验证成功 _context.Response.Write(sReplyEchoStr); } else { _context.Response.Write("您不是微信服务器,请您绕道前行!"); } } else { _context.Response.Write("您不是微信服务器,请您绕道前行!"); } }
public void ReceiveMessage() { if (this.Request.HttpMethod.ToUpper() == "GET") { this.Auth(); } else { if (!(this.Request.HttpMethod.ToUpper() == "POST")) { return; } string str1 = this.Request.QueryString["msg_signature"]; string str2 = this.Request.QueryString["timestamp"]; string str3 = this.Request.QueryString["nonce"]; WXBizMsgCrypt wxBizMsgCrypt = new WXBizMsgCrypt(this.token, this.encodingAESKey, this.corpId); Stream inputStream = HttpContext.Current.Request.InputStream; byte[] numArray = new byte[inputStream.Length]; inputStream.Read(numArray, 0, (int)inputStream.Length); string contents = Encoding.UTF8.GetString(numArray); string xml = ""; string sMsgSignature = str1; string sTimeStamp = str2; string sNonce = str3; string sPostData = contents; ref string local = ref xml; if (wxBizMsgCrypt.DecryptMsg(sMsgSignature, sTimeStamp, sNonce, sPostData, ref local) == 0) { new Message().Receive(xml); } else { RoadFlow.Platform.Log.Add("消息解密失败", contents, RoadFlow.Platform.Log.Types.微信企业号, "", "", (RoadFlow.Data.Model.Users)null); } }
/// <summary> /// 获取签名 /// </summary> /// <param name="token"></param> /// <param name="timeStamp"></param> /// <param name="nonce"></param> /// <param name="msgEncrypt"></param> /// <returns></returns> public static string GenarateSinature(string token, string timeStamp, string nonce, string msgEncrypt) { string msgSignature = null; var result = WXBizMsgCrypt.GenarateSinature(token, timeStamp, nonce, msgEncrypt, ref msgSignature); return(result == 0 ? msgSignature : result.ToString()); }
public ClientDomainContext(DomainEntity domain) : base(domain) { _msgCrypt = new WXBizMsgCrypt(domain.Token, domain.EncodingAESKey, domain.AppId); Refresh(); }
public void ReceiveMessage() { if (base.Request.HttpMethod.ToUpper() == "GET") { Auth(); } else if (base.Request.HttpMethod.ToUpper() == "POST") { string sMsgSignature = base.Request.QueryString["msg_signature"]; string sTimeStamp = base.Request.QueryString["timestamp"]; string sNonce = base.Request.QueryString["nonce"]; WXBizMsgCrypt wXBizMsgCrypt = new WXBizMsgCrypt(token, encodingAESKey, corpId); Stream inputStream = System.Web.HttpContext.Current.Request.InputStream; byte[] array = new byte[inputStream.Length]; inputStream.Read(array, 0, (int)inputStream.Length); string @string = Encoding.UTF8.GetString(array); string sMsg = ""; if (wXBizMsgCrypt.DecryptMsg(sMsgSignature, sTimeStamp, sNonce, @string, ref sMsg) == 0) { new Message().Receive(sMsg); } else { RoadFlow.Platform.Log.Add("消息解密失败", @string, RoadFlow.Platform.Log.Types.微信企业号); } } }
/// <summary> /// 微信响应方法 /// </summary> /// <param name="request"></param> /// <returns></returns> public override string Response(BaseResponseMessage response, EnterParamEntity param) { var _Response = response as VideoResponseMessage; StringBuilder result = new StringBuilder(); result.AppendFormat("<xml>"); result.AppendFormat("<ToUserName><![CDATA[{0}]]></ToUserName>", _Response.ToUserName); result.AppendFormat("<FromUserName><![CDATA[{0}]]></FromUserName>", _Response.FromUserName); result.AppendFormat("<CreateTime>{0}></CreateTime>", _Response.CreateTime); result.AppendFormat("<MsgType><![CDATA[{0}]]></MsgType>", _Response.MsgType); result.AppendFormat("<Video>"); result.AppendFormat("<MediaId><![CDATA[{0}]]></MediaId>", _Response.MediaId); if (!string.IsNullOrWhiteSpace(_Response.Title)) { result.AppendFormat("<Title><![CDATA[{0}]]></Title>", _Response.Title); } if (!string.IsNullOrWhiteSpace(_Response.Description)) { result.AppendFormat("<Description><![CDATA[{0}]]></Description>", _Response.Description); } result.AppendFormat("</Video>"); result.AppendFormat("</xml>"); if (param.IsAes) { string data = string.Empty; int encrypt = new WXBizMsgCrypt(param.token, param.EncodingAESKey, param.appid). EncryptMsg(result.ToString(), _Response.CreateTime.ToString(), param.nonce, ref data); result = new StringBuilder(data); if (encrypt != 0) { LogHelper.WriteLog("【微信响应文本消息】加密失败", LogMessageType.Error); } } return(result.ToString()); }
public XDocument Init(IEncryptPostModel postModel) { _postModel = postModel as PostModel ?? new PostModel(); //解密XML信息 var postDataStr = EcryptRequestDocument.ToString(); WXBizMsgCrypt msgCrype = new WXBizMsgCrypt(_postModel.Token, _postModel.EncodingAESKey, _postModel.AppId); string msgXml = null; var result = msgCrype.DecryptMsg(_postModel.Msg_Signature, _postModel.Timestamp, _postModel.Nonce, postDataStr, ref msgXml); //判断result类型 if (result != 0) { //验证没有通过,取消执行 CancelExcute = true; return(null); } RequestDocument = XDocument.Parse(msgXml);//完成解密 RequestMessage = RequestMessageFactory.GetRequestEntity(RequestDocument); //((RequestMessageBase)RequestMessage).FillEntityWithXml(RequestDocument); return(RequestDocument); }
/// <summary> /// 执行过滤器 /// </summary> /// <param name="input">微信的请求数据</param> /// <param name="signature">微信请求时携带的signature</param> /// <param name="nonce">微信请求时携带的nonce</param> /// <param name="timestamp">微信请求时携带的timestamp</param> /// <returns></returns> public static MiddlewareParameter Execute(string input, string signature, string nonce, string timestamp) { if (Configurations.Current.EnumMessageMode == Configurations.TransferMode.Cipher) { WXBizMsgCrypt crypt = new WXBizMsgCrypt(); var items = crypt.DecryptMsg(signature, timestamp, nonce, input); if (!items.Item1) { throw new Exception(items.Item2); } input = items.Item2; } var requestModel = input.ExXmlToEntity <RequestBase>(); requestModel.Nonce = nonce; requestModel.Timestamp = timestamp; requestModel.Signature = signature; var middleInput = new MiddlewareParameter { Input = new MiddlewareInput(input, requestModel) }; return(Execute(middleInput)); }
public ActionResult Post(string signature, string timestamp, string nonce, string echostr) { WeixinMessage message = null; var safeMode = Request.QueryString.Get("encrypt_type") == "aes"; using (var streamReader = new StreamReader(Request.InputStream)) { var decryptMsg = string.Empty; var msg = streamReader.ReadToEnd(); #region 解密 if (safeMode) { var msg_signature = Request.QueryString.Get("msg_signature"); var wxBizMsgCrypt = new WXBizMsgCrypt(WeixinConfig.Token, WeixinConfig.EncodingAESKey, WeixinConfig.AppID); var ret = wxBizMsgCrypt.DecryptMsg(msg_signature, timestamp, nonce, msg, ref decryptMsg); if (ret != 0)//解密失败 { //TODO:开发者解密失败的业务处理逻辑 //注意:本demo用log4net记录此信息,你可以用其他方法 LogWriter.Default.WriteError(string.Format("decrypt message return {0}, request body {1}", ret, msg)); } } else { decryptMsg = msg; } #endregion message = AcceptMessageAPI.Parse(decryptMsg); } var response = new WeixinExecutor().Execute(message); var encryptMsg = string.Empty; #region 加密 if (safeMode) { var msg_signature = Request.QueryString.Get("msg_signature"); var wxBizMsgCrypt = new WXBizMsgCrypt(WeixinConfig.Token, WeixinConfig.EncodingAESKey, WeixinConfig.AppID); var ret = wxBizMsgCrypt.EncryptMsg(response, timestamp, nonce, ref encryptMsg); if (ret != 0)//加密失败 { //TODO:开发者加密失败的业务处理逻辑 LogWriter.Default.WriteError(string.Format("encrypt message return {0}, response body {1}", ret, response)); } } else { encryptMsg = response; } #endregion return(new ContentResult { Content = encryptMsg, ContentType = "text/xml", ContentEncoding = System.Text.UTF8Encoding.UTF8 }); }
/// <summary> /// 验证企业号url有效性 /// </summary> /// <param name="channelId">渠道id</param> /// <param name="signature">从接收消息的URL中获取的msg_signature参数</param> /// <param name="timestamp">从接收消息的URL中获取的timestamp参数</param> /// <param name="nonce">从接收消息的URL中获取的nonce参数</param> /// <param name="echo">从接收消息的URL中获取的echostr参数。注意,此参数必须是urldecode后的值</param> /// <param name="replyEcho">解密后的明文消息内容,用于回包。注意,必须原样返回,不要做加引号或其它处理</param> /// <returns></returns> public static bool ValidateUrl(int channelId, string signature, string timestamp, string nonce, string echo, out string replyEcho) { replyEcho = string.Empty; WXBizMsgCrypt crypt = GetWXBizMsgCrypt(channelId); var result = crypt.VerifyURL(signature, timestamp, nonce, echo, ref replyEcho); return(echo.Equals(replyEcho)); }
public WxBaseController() { _setting = new AppSetting(); WeiXinAppToken = _setting.WeiXinAppToken; WeiXinEncodingAESKey = _setting.WeiXinEncodingAESKey; WeiXinAppId = _setting.WeiXinAppId; _crypt = new WXBizMsgCrypt(WeiXinAppToken, WeiXinEncodingAESKey, WeiXinAppId); }
public PassiveMessage(string xml, string timestamp, string nonce, WXBizMsgCrypt wxcpt) { Xdoc = new XDocument(); Xdoc = XDocument.Parse(xml); this.wxcpt = wxcpt; this.nonce = nonce; this.timestamp = timestamp; }
public static string DecryptMessage(string appId, string appToken, string encodingAesKey, string xmlMessage, string messageSignature, string timestamp, string nonce) { var result = ""; WXBizMsgCrypt wxBizMsgCrypt = new WXBizMsgCrypt(appToken, encodingAesKey, appId); var ret = wxBizMsgCrypt.DecryptMsg(messageSignature, timestamp, nonce, xmlMessage, ref result); return(result); }
/// <summary> /// 加密消息 /// </summary> /// <param name="token"></param> /// <param name="encodingAESKey"></param> /// <param name="corpId"></param> /// <param name="replyMsg"></param> /// <param name="timeStamp"></param> /// <param name="nonce"></param> /// <returns></returns> public static string EncryptMsg(string token, string encodingAESKey, string corpId, string replyMsg, string timeStamp, string nonce) { WXBizMsgCrypt crypt = new WXBizMsgCrypt(token, encodingAESKey, corpId); string encryptMsg = null; var result = crypt.EncryptMsg(replyMsg, timeStamp, nonce, ref encryptMsg); return(encryptMsg); }
static void Main(string[] args) { //公众平台上开发者设置的token, appID, EncodingAESKey string sToken = "QDG6eK"; string sAppID = "wx5823bf96d3bd56c7"; string sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C"; WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID); /* 1. 对用户回复的数据进行解密。 * 用户回复消息或者点击事件响应时,企业会收到回调消息,假设企业收到的推送消息: * POST /cgi-bin/wxpush? msg_signature=477715d11cdb4164915debcba66cb864d751f3e6×tamp=1409659813&nonce=1372623149 HTTP/1.1 Host: qy.weixin.qq.com Content-Length: 613 * * <xml> <ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName> <Encrypt><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo+rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT+6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6+kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r+KqCKIw+3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0+rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS+/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl/T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]></Encrypt> </xml> */ string sReqMsgSig = "477715d11cdb4164915debcba66cb864d751f3e6"; string sReqTimeStamp = "1409659813"; string sReqNonce = "1372623149"; string sReqData = "<xml><ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName><Encrypt><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo+rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT+6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6+kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r+KqCKIw+3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0+rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS+/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl/T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]></Encrypt></xml>"; string sMsg = ""; //解析之后的明文 int ret = 0; ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg); if (ret != 0) { System.Console.WriteLine("ERR: Decrypt fail, ret: " + ret); return; } System.Console.WriteLine(sMsg); /* * 2. 企业回复用户消息也需要加密和拼接xml字符串。 * 假设企业需要回复用户的消息为: * <xml> * <ToUserName><![CDATA[mycreate]]></ToUserName> * <FromUserName><![CDATA[wx5823bf96d3bd56c7]]></FromUserName> * <CreateTime>1348831860</CreateTime> <MsgType><![CDATA[text]]></MsgType> * <Content><![CDATA[this is a test]]></Content> * <MsgId>1234567890123456</MsgId> * </xml> * 生成xml格式的加密消息过程为: */ string sRespData = "<xml><ToUserName><![CDATA[mycreate]]></ToUserName><FromUserName><![CDATA[wx582测试一下中文的情况,消息长度是按字节来算的396d3bd56c7]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[this is a test]]></Content><MsgId>1234567890123456</MsgId></xml>"; string sEncryptMsg = ""; //xml格式的密文 ret = wxcpt.EncryptMsg(sRespData, sReqTimeStamp, sReqNonce, ref sEncryptMsg); System.Console.WriteLine("sEncryptMsg"); System.Console.WriteLine(sEncryptMsg); /*测试: * 将sEncryptMsg解密看看是否是原文 * */ XmlDocument doc = new XmlDocument(); doc.LoadXml(sEncryptMsg); XmlNode root = doc.FirstChild; string sig = root["MsgSignature"].InnerText; string enc = root["Encrypt"].InnerText; string timestamp = root["TimeStamp"].InnerText; string nonce = root["Nonce"].InnerText; string stmp = ""; ret = wxcpt.DecryptMsg(sig, timestamp, nonce, sEncryptMsg, ref stmp); System.Console.WriteLine("stemp"); System.Console.WriteLine(stmp + ret); return; }