You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.9 KiB

using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json.Serialization;
using Furion.JsonSerialization;
namespace GDZZ.Core;
/// <summary>
/// 小程序工具类
/// </summary>
public class MiniProgramUtil
{
/// <summary>
/// 解密数据获取小程序用户信息
/// </summary>
/// <param name="encryptedDataStr">包括敏感数据在内的完整用户信息的加密数据</param>
/// <param name="session_key">auth.code2Session获取的session_key</param>
/// <param name="iv">加密算法的初始向量</param>
/// <returns>如遇异常返回 ""</returns>
public static TelUserInfoModel AESDecrypt(string encryptedDataStr, string session_key, string iv)
{
var rlt = BasicAESDecrypt(encryptedDataStr, session_key, iv);
return !rlt.IsEmpty() ? JSON.Deserialize<TelUserInfoModel>(rlt) : null;
}
/// <summary>
/// 基础解析
/// </summary>
/// <param name="encryptedDataStr">包括敏感数据在内的完整用户信息的加密数据</param>
/// <param name="session_key">auth.code2Session获取的session_key</param>
/// <param name="iv">加密算法的初始向量</param>
/// <returns></returns>
private static string BasicAESDecrypt(string encryptedDataStr, string session_key, string iv)
{
var databyte = System.Text.Encoding.Default.GetBytes(encryptedDataStr);
// 16进制转换成byte
var encryptedData = Convert.FromBase64String(encryptedDataStr.Replace(" ",""));
var managed = new RijndaelManaged
{
Key = Convert.FromBase64String(session_key),
IV = Convert.FromBase64String(iv),
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7
};
var transform = managed.CreateDecryptor();
var finalBlock = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
var result = Encoding.Default.GetString(finalBlock);
return result;
}
public static byte[] GetByteArray(string shex)
{
string[] ssArray = shex.Split(' ');
List<byte> bytList = new List<byte>();
foreach (var s in ssArray)
{ //将十六进制的字符串转换成数值
bytList.Add(Convert.ToByte(s, 16));
} //返回字节数组
return bytList.ToArray();
}
}
/// <summary>
/// 小程序登录解密后的用户信息Model
/// </summary>
public class TelUserInfoModel
{
/// <summary>
/// 手机号
/// </summary>
[JsonPropertyName("phoneNumber")]
public string PhoneNumber { get; set; }
/// <summary>
/// 纯手机号
/// </summary>
[JsonPropertyName("purePhoneNumber")]
public string PurePhoneNumber { get; set; }
/// <summary>
/// 区号
/// </summary>
[JsonPropertyName("countryCode")]
public string CountryCode { get; set; }
}