CSharp.Template/YuanXuan.IM.Api/Helper/MobileToH5UserSign.cs

88 lines
3.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Buffers.Text;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YuanXuan.IM.Common.Exceptions;
using YuanXuan.IM.Common.Helpers;
using YuanXuan.IM.Infrastructure.Redis;
namespace YuanXuan.IM.Api.Helper
{
/// <summary>
/// 手机跳H5用户签名帮助类
/// </summary>
public static class MobileToH5UserSign
{
/// <summary>
/// 获取用户跳转H5的签名并缓存sign 1小时
/// </summary>
/// <param name="UserId"></param>
/// <param name="DataId"></param>
/// <returns></returns>
public static string GetUserSign(string UserId, long? DataId)
{
//生成sign规则为Id + "&" + userId
var sign = $"{UserId}";
if (DataId != null)
{
sign = $"{DataId}&" + sign;
}
//aes加密sign
sign = AesEncryptHelper.EncryptToShortString(sign);
//sign进行base64
// 将字符串转换为字节数组
byte[] byteArray = Encoding.UTF8.GetBytes(sign);
// 将字节数组转换为Base64字符串
string base64String = Convert.ToBase64String(byteArray);
//存储到redis中有效期1小时
RedisHelper.Instance.Set(base64String, $"{DataId}&{UserId}", TimeSpan.FromHours(1));
return base64String;
}
/// <summary>
/// 解密用户跳转H5的签名获取Id有可能为null和userId
/// </summary>
/// <param name="sign"></param>
/// <param name="parCount">正确参数个数</param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static (long? DataId, long UserId) DecryptUserSign(string sign, int parCount)
{
//判断redis中是否存在sign
var redisSign = RedisHelper.Instance.Get(sign);
if (string.IsNullOrEmpty(redisSign))
{
throw new BusinessException("链接已过期,请重新获取");
}
//sign的base64解码
byte[] decodedBytes = Convert.FromBase64String(sign);
// 转换为UTF8字符串
string decodedString = Encoding.UTF8.GetString(decodedBytes);
//解密sign
sign = AesEncryptHelper.DecryptFromShortString(decodedString);
var arr = sign.Split('&');
if (parCount!=arr.Length)
{
throw new BusinessException("参数错误");
}
if (arr.Length == 1)
{
var userId = Convert.ToInt64(arr[0]);
return (null, userId);
}
else if (true)
{
var id = Convert.ToInt64(arr[0]);
var userId = Convert.ToInt64(arr[1]);
return (id, userId);
}
else
{
throw new BusinessException("参数错误");
}
}
}
}