using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using System;
using System.Text;

namespace FactorySystemCommon
{
    public class JWTHelper
    {
        /// <summary>
        /// 加密
        /// </summary>
        public static string Encryption(object content, string keyStr = "")
        {
            string result;
            try
            {
                keyStr = AppSettingsHelper.GetAppSettingVal("ApiAuthSecretKey") + keyStr.Replace("_", "").ToLower();
                byte[] key = Encoding.UTF8.GetBytes(keyStr);
                IJwtAlgorithm algorithm = new HMACSHA256Algorithm();//加密方式
                IJsonSerializer serializer = new JsonNetSerializer();//序列化Json
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();//base64加解密
                IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);//JWT编码
                result = encoder.Encode(content, key);//生成令牌
            }
            catch (Exception ex)
            {
                throw new Exception("Auth加密发生异常,异常信息:" + ex.Message.ToString());
            }
            return result;
        }
        /// <summary>
        /// 解密
        /// </summary>
        public static T Decrypt<T>(string strKey, string keyStr = "")
        {
            keyStr = AppSettingsHelper.GetAppSettingVal("ApiAuthSecretKey") + keyStr.Replace("_", "").ToLower();
            byte[] key = Encoding.UTF8.GetBytes(keyStr);
            IJsonSerializer serializer = new JsonNetSerializer();
            IDateTimeProvider provider = new UtcDateTimeProvider();
            IJwtValidator validator = new JwtValidator(serializer, provider);
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
            //解密
            return decoder.DecodeToObject<T>(strKey, key, verify: true);
        }
    }
}
