If you have public key and private key pem files.
openssl genrsa -aes128 -passout pass:REPLACE_THIS -out privkey.pem 4096
openssl rsa -in privkey.pem -passin pass:REPLACE_THIS -pubout -out public_key.pem
In Java code, include below depedency in pom.xml:
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk18on</artifactId>
<version>1.78</version>
</dependency>
Credit to answer at link
Github Gist
Create this class:
package com.zzz.xxx.util;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class PublicPrivateKey {
// using bouncycastle to generate public key
public static PublicKey getPublicKey() throws InvalidKeySpecException, NoSuchAlgorithmException, IOException {
KeyFactory factory = KeyFactory.getInstance("RSA");
File file = new File("E:\\PATH\\public_key.pem");
try (FileReader keyReader = new FileReader(file); PemReader pemReader = new PemReader(keyReader)) {
PemObject pemObject = pemReader.readPemObject();
byte[] content = pemObject.getContent();
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(content);
PublicKey publicKey = factory.generatePublic(pubKeySpec);
return publicKey;
}
}
public static PrivateKey getPrivateKey() throws InvalidKeySpecException, NoSuchAlgorithmException, IOException {
KeyFactory factory = KeyFactory.getInstance("RSA");
File file = new File("E:\\PATH\\private_key.pem");
try (FileReader keyReader = new FileReader(file); PemReader pemReader = new PemReader(keyReader)) {
PemObject pemObject = pemReader.readPemObject();
byte[] content = pemObject.getContent();
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(content);
PrivateKey privateKey = factory.generatePrivate(privateKeySpec);
return privateKey;
}
}
}
And then use it where needed (example below):
return Jwts.builder()
.setSubject(subject)
.setIssuedAt(new Date())
.setExpiration(expiryDate)
//.signWith(SignatureAlgorithm.HS512, appProperties.getAuth().getTokenSecret())
.signWith(privateKey, SignatureAlgorithm.RS512)
.compact();