rely
Open source dependency pom reference address
<dependency> <groupId>.mingyang66</groupId> <artifactId>oceansky-jwt</artifactId> <version>4.3.2</version> </dependency>
1. How to generate RSA asymmetric key using Java code
public class RsaPemCreatorFactory { /** * Public key file name */ private static final String PUBLIC_KEY_FILE = ""; /** * Private key file name */ private static final String PRIVATE_KEY_FILE = ""; private static final String publicKeyPrefix = "PUBLIC KEY"; private static final String privateKeyPrefix = "PRIVATE KEY"; /** * algorithm */ public static final String ALGORITHM = "RSA"; public static void create(String directory) throws NoSuchAlgorithmException, IOException { // algorithm specifies that the algorithm is RSA KeyPairGenerator keyPairGenerator = (ALGORITHM); // Specify the key length to 2048 (1024); // Generate key KeyPair keyPair = (); // If the folder does not exist, create it first ((directory)); try (FileWriter writer = new FileWriter(("", directory, PRIVATE_KEY_FILE)); PemWriter pemWriter = new PemWriter(writer); FileWriter pubFileWriter = new FileWriter(("", directory, PUBLIC_KEY_FILE)); PemWriter pubPemWriter = new PemWriter(pubFileWriter)) { (new PemObject(privateKeyPrefix, ().getEncoded())); (new PemObject(publicKeyPrefix, ().getEncoded())); } catch (IOException e) { (); } } }
2. How to create RSAPublicKey and RSAPrivateKey objects
public class RsaAlgorithmFactory { public static final String N = "\n"; public static final String R = "\r"; public static final String ALGORITHM = "RSA"; /** * Get the public key object * * @param publicKey public key string * @return Public key object * @throws InvalidKeySpecException * @throws NoSuchAlgorithmException */ public static RSAPublicKey getPublicKey(String publicKey) throws InvalidKeySpecException, NoSuchAlgorithmException { if (publicKey == null || () == 0) { throw new IllegalArgumentException("Illegal Parameters"); } byte[] keyBytes = ().decode((N, "").replace(R, "").getBytes(StandardCharsets.UTF_8)); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = (ALGORITHM); return (RSAPublicKey) (x509KeySpec); } /** * Get the private key object * * @param privateKey private key string * @return Private key object * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */ public static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException { byte[] keyBytes = ().decode((N, "").replace(R, "").getBytes(StandardCharsets.UTF_8)); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = (ALGORITHM); return (RSAPrivateKey) (pkcs8KeySpec); } }
3. How to create a parsing JWT token
Create a factory method:
public class JwtFactory { /** * Create a JWT Token string * * @param builder * @param algorithm * @return token string */ public static String createJwtToken( builder, Algorithm algorithm) { // header:typ, alg algorithm return (algorithm); } /** * Object after decoding of JWT string * * @param jwtToken * @param algorithm * @return parsed jwt token object */ public static DecodedJWT verifyJwtToken(String jwtToken, Algorithm algorithm) { JWTVerifier jwtVerifier = (algorithm).build(); return (jwtToken); } }
Actual use cases:
@Test public void test() throws InvalidKeySpecException, NoSuchAlgorithmException { RSAPublicKey publicKey = (publicKey1); //(new BouncyCastleProvider()); RSAPrivateKey privateKey = (privateKey1); (()); Map<String, Object> headers = new HashMap<>(); ("ip", "123.12.123.25.12"); builder = () //JWT unique identifier jti .withJWTId(().toString()) .withHeader(headers) .withClaim("username", "Tian Runye") .withClaim("password", "dislike") //Published by iss .withIssuer("Gu Yangmin") //Published time iat .withIssuedAt((().atZone(()).toInstant())) //Audience|Recipient aud .withAudience("Tian Haimin", "Sun Yuting") //Specify that JWT cannot accept processing before the specified time nbf .withNotBefore((().plusMinutes(-1).atZone(()).toInstant())) //JWT's theme sub .withSubject("Token") //JWT's key ID (actually not used), is used to specify the signature verification key kid com. .withKeyId("sd") //JWT expiration time exp .withExpiresAt(().plusMinutes(5).atZone(()).toInstant()); String jwtToken = (builder, Algorithm.RSA256(publicKey, privateKey)); (jwtToken); DecodedJWT jwt = (jwtToken, Algorithm.RSA256(publicKey, privateKey)); (("username").asString(), "Tian Runye"); (("password").asString(), "dislike"); (("ip").asString(), "123.12.123.25.12"); ((), "Gu Yangmin"); (().get(0), "Tian Haimin"); (().get(1), "Sun Yuting"); }
This is the end of this article about using JWT to create parsing tokens and RSA asymmetric encryption. For more related content on JWT token creation, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!