我想生成 JWT 并使用 HMAC_SHA256 对其进行签名。 对于该任务,我必须使用 jose4j . 我尝试使用以下方法基于 secret 生成 key :
SecretKeySpec key = new SecretKeySpec(("secret").getBytes("UTF-8"), AlgorithmIdentifiers.HMAC_SHA512);
但它生成 40 位 key ,而使用 HMAC_SHA256 签名需要 512 位 key 。
- 主要问题 - 如何使用 jose4j 使用 HMAC_SHA512 对 token 进行签名?
- 我解决上述问题的方法产生的问题 - 如何根据 secret 字符串制作 512 位长的 secret key ?
最佳答案
Section 3.2 of JWA / RFC 7518表示必须将与散列输出大小相同或更大的 key 与 JWS HMAC SHA-2 算法一起使用(即,“HS256”为 256 位,384 位/“HS384”,& 512 位/“HS512”)。遵循 IETF 和 NIST 的建议通常是个好主意。粗略地说,HMAC 的安全性来自散列输出的大小和 key 长度,以较小者为准。因此,使用“secret”的字节作为 key 会给你一个只有 48 位长的 key ,实际上,提供的安全性甚至比它低得多,因为它是一个字典词,不管你使用的 HMAC SHA-2 算法的强度如何选择。
默认 jose4j强制执行 JWA/RFC 7518 规定的最小 key 大小。但是,正如 Hans 指出的那样,有一些方法可以告诉 jose4j 放宽 key 长度要求。这可以通过 JwtConsumer
来完成调用.setRelaxVerificationKeyValidation()
在 JwtConsumerBuilder
和 JsonWebSignature
直接与 .setDoKeyValidation(false)
.下面是一个使用 HMAC SHA256 生成和使用 JWT 的快速示例,它显示了两者。
JwtClaims claims = new JwtClaims();
claims.setExpirationTimeMinutesInTheFuture(5);
claims.setSubject("foki");
claims.setIssuer("the issuer");
claims.setAudience("the audience");
String secret = "secret";
Key key = new HmacKey(secret.getBytes("UTF-8"));
JsonWebSignature jws = new JsonWebSignature();
jws.setPayload(claims.toJson());
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
jws.setKey(key);
jws.setDoKeyValidation(false); // relaxes the key length requirement
String jwt = jws.getCompactSerialization();
System.out.println(jwt);
JwtConsumer jwtConsumer = new JwtConsumerBuilder()
.setRequireExpirationTime()
.setAllowedClockSkewInSeconds(30)
.setRequireSubject()
.setExpectedIssuer("the issuer")
.setExpectedAudience("the audience")
.setVerificationKey(key)
.setRelaxVerificationKeyValidation() // relaxes key length requirement
.build();
JwtClaims processedClaims = jwtConsumer.processToClaims(jwt);
System.out.println(processedClaims);
关于java - 如何从 secret 字符串中生成 HMAC_SHA256 key 以在 jose4j 中与 JWT 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32006323/