JWTSignerUtil
Introduction
JWT supports various signature algorithms, mainly divided into asymmetric and symmetric algorithms, and the supported algorithms are defined in SignAlgorithm.
Symmetric Signature
- HS256(HmacSHA256)
- HS384(HmacSHA384)
- HS512(HmacSHA512)
Asymmetric Signature
- RS256(SHA256withRSA)
- RS384(SHA384withRSA)
- RS512(SHA512withRSA)
- ES256(SHA256withECDSA)
- ES384(SHA384withECDSA)
- ES512(SHA512withECDSA)
Algorithms Dependent on BouncyCastle
- PS256(SHA256WithRSA/PSS)
- PS384(SHA384WithRSA/PSS)
- PS512(SHA512WithRSA/PSS)
Usage
Creating Predefined Algorithm Signer
JWTSignerUtil provides some predefined methods for creating signers of certain algorithms. For example, to create an HS256 signer:
final JWTSigner signer = JWTSignerUtil.hs256("123456".getBytes());
JWT jwt = JWT.create().setSigner(signer);Creating Custom Algorithm Signer
You can create a signer for a specific algorithm dynamically by passing in the algorithmId through JWTSignerUtil.createSigner. For example, if you need to implement the ps256 algorithm, you first need to introduce the bcprov-jdk15to18 package:
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15to18</artifactId>
<version>1.69</version>
</dependency>Then you can create the corresponding signer:
String id = "ps256";
final JWTSigner signer = JWTSignerUtil.createSigner(id, KeyUtil.generateKeyPair(AlgorithmUtil.getAlgorithm(id)));
JWT jwt = JWT.create().setSigner(signer);Implementing Custom Algorithm Signer
The JWTSigner interface is a general signer interface. To implement a custom algorithm, you just need to implement this interface.