JwtEncryption.cs 1.49 KB
using System;
using System.Collections.Generic;
using System.Text;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;

namespace Hh.Mes.Common
{
    public class JwtEncryption
    {
        public static string secret = "1q2w3e4r5t6y";

        public static string Decode(string token)
        {
            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)
        {
            double exp = (DateTime.UtcNow.AddSeconds(60) - new DateTime(1970, 1, 1)).TotalSeconds;
            value.Add("exp", exp);
            var algorithm = new HMACSHA256Algorithm();
            var serializer = new JsonNetSerializer();
            var urlEncoder = new JwtBase64UrlEncoder();
            var encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
            return encoder.Encode(value, secret);
        }
    }
}