码迷,mamicode.com
首页 > 其他好文 > 详细

JwtHashAlgorithm 加密

时间:2018-01-18 15:07:30      阅读:331      评论:0      收藏:0      [点我收藏+]

标签:name   for   oar   tostring   text   expected   key   dict   collect   

         //自定义对象
            var payload = new {name="张三",age=110,time=DateTime.Now };

            string key = "这是什么?";

           string token=  JsonWebToken.Encode(payload, Encoding.UTF8.GetBytes(key), JwtHashAlgorithm.HS384);

            //获取payload对象
            var j2 = JsonWebToken.Decode(token, key, true);

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using Newtonsoft.Json;

namespace WindowsFormsApp10.Models
{
    public enum JwtHashAlgorithm
    {
        RS256,
        HS384,
        HS512
    }
    public class JsonWebToken
    {
        private static Dictionary<JwtHashAlgorithm, Func<byte[], byte[], byte[]>> HashAlgorithms;
        private static byte[] bb = new byte[10];
        static JsonWebToken()
        {

            HashAlgorithms = new Dictionary<JwtHashAlgorithm, Func<byte[], byte[], byte[]>>
            {
                {
                    JwtHashAlgorithm.RS256,
                    (x,y)=>{using(var h256=new HMACSHA256(x)){return h256.ComputeHash(y);}}},
                { JwtHashAlgorithm.HS384, (x,y)=>{using(var h256=new HMACSHA384(x)){return h256.ComputeHash(y);}} },
                { JwtHashAlgorithm.HS512, (x,y)=>{using(var h256=new HMACSHA512(x)){return h256.ComputeHash(y);}} }
            };
        }
        public static string Encode(object payload, byte[] keyBytes, JwtHashAlgorithm algorithm)
        {
            List<string> segments = new List<string>();
            var header = new { alg = algorithm.ToString(), typ = "JWT" };
            byte[] headerBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(header, Formatting.None));
            byte[] payloadBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload, Formatting.None));
            segments.Add(Base64UrlEncode(headerBytes));
            segments.Add(Base64UrlEncode(payloadBytes));

            string stringToSign = string.Join(".", segments.ToArray());
            byte[] bytesToSign = Encoding.UTF8.GetBytes(stringToSign);

            byte[] signature = HashAlgorithms[algorithm](keyBytes, bytesToSign);
            segments.Add(Base64UrlEncode(signature));

            return string.Join(".", segments);
        }
        private static string Base64UrlEncode(byte[] input)
        {
            string output = Convert.ToBase64String(input);
            output = output.Split(=)[0];
            output = output.Replace("+", "-").Replace("/", "_");
            return output;
        }
        public static string Decode(string token, string key, bool verify)
        {
            string[] parts = token.Split(.);
            string header = parts[0];
            string payload = parts[1];
            byte[] crypto = Base64UrlDecode(parts[2]);
            string headerJson = Encoding.UTF8.GetString(Base64UrlDecode(header));
            var headerData = Newtonsoft.Json.Linq.JObject.Parse(headerJson);
            string payloadJson = Encoding.UTF8.GetString(Base64UrlDecode(payload));
            var payloadDaata = Newtonsoft.Json.Linq.JObject.Parse(payloadJson);
            if (verify)
            {
                var bytesToSign = Encoding.UTF8.GetBytes(header + "." + payload);
                byte[] keyBytes = Encoding.UTF8.GetBytes(key);
                string algorithm = (string)headerData["alg"];
                var signature = HashAlgorithms[GetHashAlgorithm(algorithm)](keyBytes, bytesToSign);

                var decodedCrypto = Convert.ToBase64String(crypto);
                var decodedSignature = Convert.ToBase64String(signature);
                if (decodedCrypto != decodedSignature)
                {
                    throw new ApplicationException(string.Format("Invalid signature. Expected {0} got {1}", decodedCrypto, decodedSignature));
                }
            }
            return payloadDaata.ToString();
        }

        private static JwtHashAlgorithm GetHashAlgorithm(string algorithm)
        {
            switch (algorithm)
            {
                case "RS256":
                    return JwtHashAlgorithm.RS256;
                case "HS384":
                    return JwtHashAlgorithm.HS384;
                case "HS512":
                    return JwtHashAlgorithm.HS512;
                default:
                    throw new InvalidOperationException("Algorithm not supported.");
            }
        }
        private static byte[] Base64UrlDecode(string input)
        {
            string output = input.Replace(-, +).Replace(_, /);
            switch (output.Length % 4)
            {
                case 0:
                    break;
                case 2:
                    output += "==";
                    break;
                case 3:
                    output += "=";
                    break;
                default:
                    throw new System.Exception("Illegal base64url string!");
            }
            return Convert.FromBase64String(output);
        }

    }
}

 

完!

 

JwtHashAlgorithm 加密

标签:name   for   oar   tostring   text   expected   key   dict   collect   

原文地址:https://www.cnblogs.com/wwz-wwz/p/8309945.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!