您好,登錄后才能下訂單哦!
這篇文章主要講解了“如何實(shí)現(xiàn).NET微信小程序用戶數(shù)據(jù)的簽名驗(yàn)證功能”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來(lái)研究和學(xué)習(xí)“如何實(shí)現(xiàn).NET微信小程序用戶數(shù)據(jù)的簽名驗(yàn)證功能”吧!
微信小程序時(shí)下大熱,抱著學(xué)習(xí)的心態(tài)了解了一下,目前沒(méi)有搜到完整的.NET用戶數(shù)據(jù)簽名驗(yàn)證和解密代碼,于是就寫了一點(diǎn)。
簡(jiǎn)單使用方法:
1、客戶端調(diào)用wx.getUserInfo方法,服務(wù)端創(chuàng)建WeChatLoginInfo類的實(shí)例接收客戶端發(fā)來(lái)的數(shù)據(jù);
2、服務(wù)端新建WeChatAppDecrypt類的實(shí)例,初始化此類時(shí)需傳入appId與AppSecret用于驗(yàn)證;
3、調(diào)用WeChatAppDecrypt類中的Decrypt方法,傳入步驟1中獲取的WechatLoginInfo實(shí)例;
4、得到WechatUserInfo類的實(shí)例,其中就是解密好的數(shù)據(jù)。
話不多說(shuō),注釋比較詳盡,感興趣的朋友可以參考。
using System; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using Newtonsoft.Json; using System.Security.Cryptography; using System.Text; namespace BroadSky.WeChatAppDecrypt { /// <summary> /// 處理微信小程序用戶數(shù)據(jù)的簽名驗(yàn)證和解密 /// </summary> public class WeChatAppDecrypt { private string appId; private string appSecret; /// <summary> /// 構(gòu)造函數(shù) /// </summary> /// <param name="appId">應(yīng)用程序的AppId</param> /// <param name="appSecret">應(yīng)用程序的AppSecret</param> public WeChatAppDecrypt(string appId, string appSecret) { this.appId = appId; this.appSecret = appSecret; return; } /// <summary> /// 獲取OpenId和SessionKey的Json數(shù)據(jù)包 /// </summary> /// <param name="code">客戶端發(fā)來(lái)的code</param> /// <returns>Json數(shù)據(jù)包</returns> private string GetOpenIdAndSessionKeyString(string code) { string temp = "https://api.weixin.qq.com/sns/jscode2session?" + "appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code"; return GetResponse(temp); } /// <summary> /// 反序列化包含OpenId和SessionKey的Json數(shù)據(jù)包 /// </summary> /// <param name="code">Json數(shù)據(jù)包</param> /// <returns>包含OpenId和SessionKey的類</returns> public OpenIdAndSessionKey DecodeOpenIdAndSessionKey(WechatLoginInfo loginInfo) { OpenIdAndSessionKey oiask = JsonConvert.DeserializeObject<OpenIdAndSessionKey>(GetOpenIdAndSessionKeyString(loginInfo.code)); if (!String.IsNullOrEmpty(oiask.errcode)) return null; return oiask; } /// <summary> /// 根據(jù)微信小程序平臺(tái)提供的簽名驗(yàn)證算法驗(yàn)證用戶發(fā)來(lái)的數(shù)據(jù)是否有效 /// </summary> /// <param name="rawData">公開(kāi)的用戶資料</param> /// <param name="signature">公開(kāi)資料攜帶的簽名信息</param> /// <param name="sessionKey">從服務(wù)端獲取的SessionKey</param> /// <returns>True:資料有效,F(xiàn)alse:資料無(wú)效</returns> public bool VaildateUserInfo(string rawData, string signature, string sessionKey) { //創(chuàng)建SHA1簽名類 SHA1 sha1 = new SHA1CryptoServiceProvider(); //編碼用于SHA1驗(yàn)證的源數(shù)據(jù) byte[] source = Encoding.UTF8.GetBytes(rawData + sessionKey); //生成簽名 byte[] target = sha1.ComputeHash(source); //轉(zhuǎn)化為string類型,注意此處轉(zhuǎn)化后是中間帶短橫杠的大寫字母,需要剔除橫杠轉(zhuǎn)小寫字母 string result = BitConverter.ToString(target).Replace("-","").ToLower(); //比對(duì),輸出驗(yàn)證結(jié)果 return signature == result; } /// <summary> /// 根據(jù)微信小程序平臺(tái)提供的簽名驗(yàn)證算法驗(yàn)證用戶發(fā)來(lái)的數(shù)據(jù)是否有效 /// </summary> /// <param name="loginInfo">登陸信息</param> /// <param name="sessionKey">從服務(wù)端獲取的SessionKey</param> /// <returns>True:資料有效,F(xiàn)alse:資料無(wú)效</returns> public bool VaildateUserInfo(WechatLoginInfo loginInfo, string sessionKey) { return VaildateUserInfo(loginInfo.rawData, loginInfo.signature, sessionKey); } /// <summary> /// 根據(jù)微信小程序平臺(tái)提供的簽名驗(yàn)證算法驗(yàn)證用戶發(fā)來(lái)的數(shù)據(jù)是否有效 /// </summary> /// <param name="loginInfo">登陸信息</param> /// <param name="idAndKey">包含OpenId和SessionKey的類</param> /// <returns>True:資料有效,F(xiàn)alse:資料無(wú)效</returns> public bool VaildateUserInfo(WechatLoginInfo loginInfo, OpenIdAndSessionKey idAndKey) { return VaildateUserInfo(loginInfo, idAndKey.session_key); } /// <summary> /// 根據(jù)微信小程序平臺(tái)提供的解密算法解密數(shù)據(jù) /// </summary> /// <param name="encryptedData">加密數(shù)據(jù)</param> /// <param name="iv">初始向量</param> /// <param name="sessionKey">從服務(wù)端獲取的SessionKey</param> /// <returns></returns> public WechatUserInfo Decrypt(string encryptedData, string iv, string sessionKey) { WechatUserInfo userInfo; //創(chuàng)建解密器生成工具實(shí)例 AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); //設(shè)置解密器參數(shù) aes.Mode = CipherMode.CBC; aes.BlockSize = 128; aes.Padding = PaddingMode.PKCS7; //格式化待處理字符串 byte[] byte_encryptedData = Convert.FromBase64String(encryptedData); byte[] byte_iv = Convert.FromBase64String(iv); byte[] byte_sessionKey = Convert.FromBase64String(sessionKey); aes.IV = byte_iv; aes.Key = byte_sessionKey; //根據(jù)設(shè)置好的數(shù)據(jù)生成解密器實(shí)例 ICryptoTransform transform = aes.CreateDecryptor(); //解密 byte [] final = transform.TransformFinalBlock(byte_encryptedData, 0, byte_encryptedData.Length); //生成結(jié)果 string result = Encoding.UTF8.GetString(final); //反序列化結(jié)果,生成用戶信息實(shí)例 userInfo = JsonConvert.DeserializeObject<WechatUserInfo>(result); return userInfo; } /// <summary> /// 根據(jù)微信小程序平臺(tái)提供的解密算法解密數(shù)據(jù),推薦直接使用此方法 /// </summary> /// <param name="loginInfo">登陸信息</param> /// <returns>用戶信息</returns> public WechatUserInfo Decrypt(WechatLoginInfo loginInfo) { if (loginInfo == null) return null; if (String.IsNullOrEmpty(loginInfo.code)) return null; OpenIdAndSessionKey oiask = DecodeOpenIdAndSessionKey(loginInfo); if (oiask == null) return null; if (!VaildateUserInfo(loginInfo, oiask)) return null; WechatUserInfo userInfo = Decrypt(loginInfo.encryptedData, loginInfo.iv, oiask.session_key); return userInfo; } /// <summary> /// GET請(qǐng)求 /// </summary> /// <param name="url"></param> /// <returns></returns> private string GetResponse(string url) { if (url.StartsWith("https")) System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = httpClient.GetAsync(url).Result; if (response.IsSuccessStatusCode) { string result = response.Content.ReadAsStringAsync().Result; return result; } return null; } } /// <summary> /// 微信小程序登錄信息結(jié)構(gòu) /// </summary> public class WechatLoginInfo { public string code { get; set; } public string encryptedData { get; set; } public string iv { get; set; } public string rawData { get; set; } public string signature { get; set; } } /// <summary> /// 微信小程序用戶信息結(jié)構(gòu) /// </summary> public class WechatUserInfo { public string openId { get; set; } public string nickName { get; set; } public string gender { get; set; } public string city { get; set; } public string province { get; set; } public string country { get; set; } public string avatarUrl { get; set; } public string unionId { get; set; } public Watermark watermark { get; set; } public class Watermark { public string appid { get; set; } public string timestamp { get; set; } } } /// <summary> /// 微信小程序從服務(wù)端獲取的OpenId和SessionKey信息結(jié)構(gòu) /// </summary> public class OpenIdAndSessionKey { public string openid { get; set; } public string session_key { get; set; } public string errcode { get; set; } public string errmsg { get; set; } } }
感謝各位的閱讀,以上就是“如何實(shí)現(xiàn).NET微信小程序用戶數(shù)據(jù)的簽名驗(yàn)證功能”的內(nèi)容了,經(jīng)過(guò)本文的學(xué)習(xí)后,相信大家對(duì)如何實(shí)現(xiàn).NET微信小程序用戶數(shù)據(jù)的簽名驗(yàn)證功能這一問(wèn)題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。