博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JwtHashAlgorithm 加密
阅读量:4658 次
发布时间:2019-06-09

本文共 4961 字,大约阅读时间需要 16 分钟。

//自定义对象            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
> HashAlgorithms; private static byte[] bb = new byte[10]; static JsonWebToken() { HashAlgorithms = new Dictionary
> { { 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
segments = new List
(); 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); } }}

 

完!

 

转载于:https://www.cnblogs.com/wwz-wwz/p/8309945.html

你可能感兴趣的文章
Struts04---命名空间的查询顺序以及默认执行的Action
查看>>
关于Mapper、Reducer的个人总结(转)
查看>>
JS基础:this的指向以及call、apply的作用
查看>>
Linux下PS1、PS2、PS3、PS4使用详解
查看>>
“井号键”用英语怎么说?
查看>>
工作进展小结
查看>>
es6之后,真的不需要知道原型链了吗?
查看>>
笔记第四天
查看>>
rabbitmq学习-如何安装rabbitmq
查看>>
java 多线程 原子性
查看>>
Effective C++ 条款04
查看>>
STM32F407 串口通信:分类&常见接口 个人笔记
查看>>
qt 打包发布 获取dll
查看>>
辗转相除法、更相减损术(九章算术) 还是有点迷糊,
查看>>
Phone List
查看>>
Naive and Silly Muggles
查看>>
node.js服务器
查看>>
Java进击C#——语法之ADO.NET
查看>>
[转]理解I/O Completion Port(完成端口)
查看>>
bzoj 4403: 序列统计
查看>>