Geração e validação de tokens JWT com criptografia assimétrica RSA-256 usando keystore JKS. Use quando: implementar autenticação stateless em APIs REST, integrar microserviços, ou habilitar autenticação para clientes móveis/SPA.
Implementação de JSON Web Tokens (JWT) com assinatura RSA-256 (chave pública/privada) para autenticação stateless em APIs.
Gere as chaves RSA usando script Java:
import java.security.*;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
public class GeradorSecret {
public static void main(String[] args) throws Exception {
// Gerar par de chaves RSA-2048
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair pair = keyGen.generateKeyPair();
// Criar keystore JKS
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
ks.setKeyEntry("jwtKey", pair.getPrivate(),
"senha-forte-aqui".toCharArray(),
new Certificate[]{/* certificado gerado */});
// Salvar keystore
try (FileOutputStream fos = new FileOutputStream("jwt-keystore.jks")) {
ks.store(fos, "senha-forte-aqui".toCharArray());
}
// Salvar senha codificada em Base64
String encoded = Base64.getEncoder().encodeToString(
"senha-forte-aqui".getBytes());
Files.write(Paths.get("jwt-secret.key"), encoded.getBytes());
}
}
Estrutura resultante:
src/main/resources/secret/
├── jwt-keystore.jks # Contém chave privada + certificado
└── jwt-secret.key # Senha do keystore (Base64)