這篇文章主要講解了“如何實現(xiàn).NET微信小程序用戶數(shù)據(jù)的簽名驗證功能”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“如何實現(xiàn).NET微信小程序用戶數(shù)據(jù)的簽名驗證功能”吧!
微信小程序時下大熱,抱著學(xué)習(xí)的心態(tài)了解了一下,目前沒有搜到完整的.NET用戶數(shù)據(jù)簽名驗證和解密代碼,于是就寫了一點。
簡單使用方法:
1、客戶端調(diào)用wx.getUserInfo方法,服務(wù)端創(chuàng)建WeChatLoginInfo類的實例接收客戶端發(fā)來的數(shù)據(jù);
2、服務(wù)端新建WeChatAppDecrypt類的實例,初始化此類時需傳入appId與AppSecret用于驗證;
3、調(diào)用WeChatAppDecrypt類中的Decrypt方法,傳入步驟1中獲取的WechatLoginInfo實例;
4、得到WechatUserInfo類的實例,其中就是解密好的數(shù)據(jù)。
話不多說,注釋比較詳盡,感興趣的朋友可以參考。
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 { ////// 處理微信小程序用戶數(shù)據(jù)的簽名驗證和解密 /// public class WeChatAppDecrypt { private string appId; private string appSecret; ////// 構(gòu)造函數(shù) /// /// 應(yīng)用程序的AppId /// 應(yīng)用程序的AppSecret public WeChatAppDecrypt(string appId, string appSecret) { this.appId = appId; this.appSecret = appSecret; return; } ////// 獲取OpenId和SessionKey的Json數(shù)據(jù)包 /// /// 客戶端發(fā)來的code ///Json數(shù)據(jù)包 private string GetOpenIdAndSessionKeyString(string code) { string temp = "/tupian/20230522/jscode2session "appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code"; return GetResponse(temp); } ////// 反序列化包含OpenId和SessionKey的Json數(shù)據(jù)包 /// /// Json數(shù)據(jù)包 ///包含OpenId和SessionKey的類 public OpenIdAndSessionKey DecodeOpenIdAndSessionKey(WechatLoginInfo loginInfo) { OpenIdAndSessionKey oiask = JsonConvert.DeserializeObject(GetOpenIdAndSessionKeyString(loginInfo.code)); if (!String.IsNullOrEmpty(oiask.errcode)) return null; return oiask; } /// /// 根據(jù)微信小程序平臺提供的簽名驗證算法驗證用戶發(fā)來的數(shù)據(jù)是否有效 /// /// 公開的用戶資料 /// 公開資料攜帶的簽名信息 /// 從服務(wù)端獲取的SessionKey ///True:資料有效,F(xiàn)alse:資料無效 public bool VaildateUserInfo(string rawData, string signature, string sessionKey) { //創(chuàng)建SHA1簽名類 SHA1 sha1 = new SHA1CryptoServiceProvider(); //編碼用于SHA1驗證的源數(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(); //比對,輸出驗證結(jié)果 return signature == result; } ////// 根據(jù)微信小程序平臺提供的簽名驗證算法驗證用戶發(fā)來的數(shù)據(jù)是否有效 /// /// 登陸信息 /// 從服務(wù)端獲取的SessionKey ///True:資料有效,F(xiàn)alse:資料無效 public bool VaildateUserInfo(WechatLoginInfo loginInfo, string sessionKey) { return VaildateUserInfo(loginInfo.rawData, loginInfo.signature, sessionKey); } ////// 根據(jù)微信小程序平臺提供的簽名驗證算法驗證用戶發(fā)來的數(shù)據(jù)是否有效 /// /// 登陸信息 /// 包含OpenId和SessionKey的類 ///True:資料有效,F(xiàn)alse:資料無效 public bool VaildateUserInfo(WechatLoginInfo loginInfo, OpenIdAndSessionKey idAndKey) { return VaildateUserInfo(loginInfo, idAndKey.session_key); } ////// 根據(jù)微信小程序平臺提供的解密算法解密數(shù)據(jù) /// /// 加密數(shù)據(jù) /// 初始向量 /// 從服務(wù)端獲取的SessionKey ///public WechatUserInfo Decrypt(string encryptedData, string iv, string sessionKey) { WechatUserInfo userInfo; //創(chuàng)建解密器生成工具實例 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ù)生成解密器實例 ICryptoTransform transform = aes.CreateDecryptor(); //解密 byte [] final = transform.TransformFinalBlock(byte_encryptedData, 0, byte_encryptedData.Length); //生成結(jié)果 string result = Encoding.UTF8.GetString(final); //反序列化結(jié)果,生成用戶信息實例 userInfo = JsonConvert.DeserializeObject (result); return userInfo; } /// /// 根據(jù)微信小程序平臺提供的解密算法解密數(shù)據(jù),推薦直接使用此方法 /// /// 登陸信息 ///用戶信息 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; } ////// GET請求 /// /// ///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; } } /// /// 微信小程序登錄信息結(jié)構(gòu) /// 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; } } ////// 微信小程序用戶信息結(jié)構(gòu) /// 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; } } } ////// 微信小程序從服務(wù)端獲取的OpenId和SessionKey信息結(jié)構(gòu) /// public class OpenIdAndSessionKey { public string openid { get; set; } public string session_key { get; set; } public string errcode { get; set; } public string errmsg { get; set; } } }
感謝各位的閱讀,以上就是“如何實現(xiàn).NET微信小程序用戶數(shù)據(jù)的簽名驗證功能”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對如何實現(xiàn).NET微信小程序用戶數(shù)據(jù)的簽名驗證功能這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是創(chuàng)新互聯(lián)網(wǎng)站建設(shè)公司,,小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!