JWT(JSON Web Token) Java与.Net简单编码实现
Posted lywJee
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JWT(JSON Web Token) Java与.Net简单编码实现相关的知识,希望对你有一定的参考价值。
参考
Java与.Net实现实现
// java HMacsha256 private static final String MAC_INSTANCE_NAME = "HMacSHA256"; public static String Hmacsha256(String secret, String message) throws NoSuchAlgorithmException, InvalidKeyException { Mac hmac_sha256 = Mac.getInstance(MAC_INSTANCE_NAME); SecretKeySpec key = new SecretKeySpec(secret.getBytes(), MAC_INSTANCE_NAME); hmac_sha256.init(key); byte[] buff = hmac_sha256.doFinal(message.getBytes()); return Base64.encodeBase64URLSafeString(buff); } // java jwt @Test public void testJWT() throws InvalidKeyException, NoSuchAlgorithmException { String secret = "eerp"; String header = "{\\"type\\":\\"JWT\\",\\"alg\\":\\"HS256\\"}"; String claim = "{\\"iss\\":\\"cnooc\\", \\"sub\\":\\"yrm\\", \\"username\\":\\"yrm\\", \\"admin\\":true}"; String base64Header = Base64.encodeBase64URLSafeString(header.getBytes()); String base64Claim = Base64.encodeBase64URLSafeString(claim.getBytes()); String signature = ShaUtil.Hmacsha256(secret, base64Header + "." + base64Claim); String jwt = base64Header + "." + base64Claim + "." + signature; System.out.println(jwt); }
// c# Hmacsha256
protected String HMacSha256Hash(String key, String message)
{
var keyBytes = Encoding.UTF8.GetBytes(key);
using (var hmacsha256 = new HMACSHA256(keyBytes))
{
var buffer = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(message));
var b64 = Base64UrlSafeString(buffer);
return b64;
}
}
protected String Base64UrlSafeString(Byte[] bytes)
{
var b64 = Convert.ToBase64String(bytes);
return b64.Replace("=", "").Replace("+", "-").Replace("/", "_");
}
// c# jwt
[Test]
public void testJWT()
{
String secret = "eerp";
String header = "{\\"type\\":\\"JWT\\",\\"alg\\":\\"HS256\\"}";
String claim = "{\\"iss\\":\\"cnooc\\", \\"sub\\":\\"yrm\\", \\"username\\":\\"yrm\\", \\"admin\\":true}";
var encoding = Encoding.UTF8;
var base64Header = Base64UrlSafeString(encoding.GetBytes(header));
var base64Claim = Base64UrlSafeString(encoding.GetBytes(claim));
var signature = HMacSha256Hash(secret, base64Header + "." + base64Claim);
var jwt = base64Header + "." + base64Claim + "." + signature;
Console.WriteLine(jwt);
}
以上是关于JWT(JSON Web Token) Java与.Net简单编码实现的主要内容,如果未能解决你的问题,请参考以下文章
android 中使用jwt token(json web token)--java
在 node.js 中生成的 JWT(JSON Web Token) 未在 java 中验证
JWT( JSON Web Token )的 实践,以及与 Session 对比