标签:public ide log XML c89 elm 私有 oob lock
在小程序中通过 wx.getUserInfo 获取用户信息,而UnionId 只有关主了公众号才会返回,不关注公众号想获取UnionId则需要我们从返回的 encryptedData 中解码从而获取UnionId。
解密方法查了一下,这边选择的 GitHub地址
帮助类:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace YouNameSpace { using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; /// <summary> /// 签名及加密帮助类 /// </summary> public static class EncryptHelper { #region 私有方法 private static byte[] AES_Decrypt(String Input, byte[] Iv, byte[] Key) { RijndaelManaged aes = new RijndaelManaged(); #if NET45 #else //SymmetricAlgorithm aes = Aes.Create(); #endif aes.KeySize = 128;//原始:256 aes.BlockSize = 128; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.Key = Key; aes.IV = Iv; var decrypt = aes.CreateDecryptor(aes.Key, aes.IV); byte[] xBuff = null; using (var ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write)) { byte[] xXml = Convert.FromBase64String(Input); byte[] msg = new byte[xXml.Length + 32 - xXml.Length % 32]; Array.Copy(xXml, msg, xXml.Length); cs.Write(xXml, 0, xXml.Length); } xBuff = decode2(ms.ToArray()); } return xBuff; } private static byte[] decode2(byte[] decrypted) { int pad = (int)decrypted[decrypted.Length - 1]; if (pad < 1 || pad > 32) { pad = 0; } byte[] res = new byte[decrypted.Length - pad]; Array.Copy(decrypted, 0, res, 0, decrypted.Length - pad); return res; } #endregion /// <summary> /// 解密所有消息的基础方法 /// </summary> /// <param name = "sessionKey" > 储存在 SessionBag 中的当前用户 会话 SessionKey</param> /// <param name = "encryptedData" > 接口返回数据中的 encryptedData 参数</param> /// <param name = "iv" > 接口返回数据中的 iv 参数,对称解密算法初始向量</param> // / <returns></returns> public static string DecodeEncryptedData(string sessionKey, string encryptedData, string iv) { var aesCipher = Convert.FromBase64String(encryptedData); var aesKey = Convert.FromBase64String(sessionKey); var aesIV = Convert.FromBase64String(iv); var result = AES_Decrypt(encryptedData, aesIV, aesKey); var resultStr = Encoding.UTF8.GetString(result); return resultStr; } } }
后台需要小程序传递三个参数给我们进行解密
String : sessionKey :加密的签名(注:这个参数需要动态的获取,每次返回的都不一样):接口地址 通过wx.login 获取 code然后再调用改接口返回的 会话密码
String : encryptedData: 完整用户信息的加密数据
String : iv:加密算法的初始向量 String
把这三给参数传给我们的后台进行解密
主要方法:
string result =EncryptHelper.DecodeEncryptedData(sessionKey, encryptedData, iv); var dy = DynamicExtensions.JsonToDynamic<JObject>(result); string nickName = dy["nickName"] + ""; string sex = dy["gender"] + ""; string city = dy["city"] + ""; string province = dy["province"] + ""; string country = dy["country"] + ""; string headUrl = dy["avatarUrl"] + ""; string unionId = dy["unionId"] + "";
.NET 小程序 wx.getUserInfo(OBJECT) 解密 encryptedData 来获取UnionId
标签:public ide log XML c89 elm 私有 oob lock
原文地址:https://www.cnblogs.com/Sea1ee/p/9627021.html