JwtEncryption.cs 2.1 KB
using System;
using System.Collections.Generic;
using JWT;
using JWT.Algorithms;
using JWT.Builder;
using JWT.Serializers;

namespace Hh.Mes.Common
{
    public class JwtEncryption
    {
        /// <summary>
        /// 默认密钥
        /// </summary>
        public readonly static string _secret = "1q2w3e4r5t6y";

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="token"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        public static string Decode(string token, string secret = null)
        {
            if (string.IsNullOrWhiteSpace(secret))
            {
                secret = _secret;
            }
            var serializer = new JsonNetSerializer();
            var provider = new UtcDateTimeProvider();
            var validator = new JwtValidator(serializer, provider);
            var urlEncoder = new JwtBase64UrlEncoder();
            var alg = new HMACSHA256Algorithm();
            var decoder = new JwtDecoder(serializer, validator, urlEncoder, alg);

            //{"loginName":"admin","iss":"dims","exp":1637637033}
            return decoder.Decode(token, secret, false);
        }

        /// <summary>
        /// 加密{ "loginName", "tuzhuang" }, { "ISSURE", "hh2.0" },,          
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string Encode(Dictionary<string, object> value, string secret = null)
        {
            if (string.IsNullOrWhiteSpace(secret))
            {
                secret = _secret;
            }

            //过期时间
            if (!value.ContainsKey("exp"))
            {
                //有效期1天
                value.Add("exp", DateTimeOffset.UtcNow.AddDays(1).ToUnixTimeSeconds().ToString());
            }

            var algorithm = new HMACSHA256Algorithm();
            var serializer = new JsonNetSerializer();
            var urlEncoder = new JwtBase64UrlEncoder();
            var encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
            return encoder.Encode(value, secret);
        }
    }
}