zoukankan      html  css  js  c++  java
  • JwtHashAlgorithm 加密

             //自定义对象
                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);
            }
    
        }
    }

    完!

  • 相关阅读:
    Linux查看程序端口占用情况
    详解大端模式和小端模式
    HDFS之二:HDFS文件系统JavaAPI接口
    HBase之四--(1):Java操作Hbase进行建表、删表以及对数据进行增删改查,条件查询
    HBase之七:事务和并发控制机制原理
    HBase源码分析:HTable put过程
    QueryPerformanceFrequency使用方法--Windows高精度定时计数
    mongoDB的基本使用----飞天博客
    Android使用DOM生成和输出XML格式数据
    黑马程序猿_Java 代理机制学习总结
  • 原文地址:https://www.cnblogs.com/wwz-wwz/p/8309945.html
Copyright © 2011-2022 走看看