参考
Java与.Net实现实现
// java HMacsha256private 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@Testpublic 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# Hmacsha256protected 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);}
结果:
eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFMyNTYifQ.eyJpc3MiOiJjbm9vYyIsICJzdWIiOiJ5cm0iLCAidXNlcm5hbWUiOiJ5cm0iLCAiYWRtaW4iOnRydWV9.sAHcCnpnsPA0T9i-Ig9oZnVq3N0-kK_aCwlkzFOkrH8