参考
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);
}
原文地址:https://www.cnblogs.com/lywJ/p/10528491.html
时间: 2024-10-10 09:15:30