码迷,mamicode.com
首页 > 编程语言 > 详细

JWT(JSON Web Token) Java与.Net简单编码实现

时间:2019-03-14 10:28:44      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:except   convert   uil   min   init   out   ati   col   实现   

参考

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简单编码实现

标签:except   convert   uil   min   init   out   ati   col   实现   

原文地址:https://www.cnblogs.com/lywJ/p/10528491.html

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