JwtHashAlgorithm 加密

Posted 王炜忠

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
        }

    }
}

 

完!

 

以上是关于JwtHashAlgorithm 加密的主要内容,如果未能解决你的问题,请参考以下文章

可以解密加密数据的片段吗?

论如何设计一款端对端加密通讯软件

使用ffmpeg视频切片并加密

WPYOU主题加密码代码的解码

Laravel基本使用

(转)博客园登陆__JSEncrypt 分析