In some cases, such as JWT, you want to sign / verify using the public / private key on the server. I think that the JWT library side provides a method to create a key pair, but if you use it, a key pair will be generated every time you start the application. If you can't disable the last issued JWT each time you boot, you'll be using a fixed key pair.
These days, ECDSA seems to be used more often than RSA because it is smaller in size and has the same level of cryptographic strength.
Create in pem format.
openssl ecparam -genkey -name secp256k1 -out key-pair.pem
openssl pkcs8 -topk8 -inform pem -in key-pair.pem -outform pem -nocrypt -out private.pem
openssl ec -in key-pair.pem -pubout -outform pem -out public.pem
private key
private key is
----- BEGIN PRIVATE KEY -----
, ----- END PRIVATE KEY -----
and trim the line feed codeimport java.nio.file.Files;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
String privatePem = new String(Files.readAllBytes(path))
.replaceAll("\\r\\n", "")
.replaceAll("\\n", "")
.replaceAll("-----BEGIN PRIVATE KEY-----", "")
.replaceAll("-----END PRIVATE KEY-----", "");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privatePem));
PrivateKey privateKey = KeyFactory.getInstance("EC").generatePrivate(keySpec);
public key
----- BEGIN PUBLIC KEY -----
, ----- END PUBLIC KEY -----
and trim the line feed codeString publicPem = new String(Files.readAllBytes(jwtSettings.getPublicKeyAsPath()))
.replaceAll("\\r\\n", "")
.replaceAll("\\n", "")
.replaceAll("-----BEGIN PUBLIC KEY-----", "")
.replaceAll("-----END PUBLIC KEY-----", "");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicPem));
PublicKey publicKey = KeyFactory.getInstance(jwtSettings.getAlgorithm()).generatePublic(keySpec);
Recommended Posts