Skip to content

Instantly share code, notes, and snippets.

@Symryvvin
Last active March 3, 2021 10:15
Show Gist options
  • Select an option

  • Save Symryvvin/16dfb69cf14f68bab8e4fecd9d0edc6d to your computer and use it in GitHub Desktop.

Select an option

Save Symryvvin/16dfb69cf14f68bab8e4fecd9d0edc6d to your computer and use it in GitHub Desktop.
Use RSA key for generate and validate JWT

To generate new RSA256 key use commands:

openssl genrsa -out jwt.pem 2048
openssl rsa -in jwt.pem -pubout -outform PEM -out jwt_public_key.pem
openssl pkcs8 -topk8 -inform PEM -in jwt.pem -out jwt_private_key.pem -nocrypt

jwt_public_key.pem:

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDGhij7UtZU765L8hUO97e7h4wT
CjzTPSOj1UipZN(...other encoded data)
-----END PUBLIC KEY-----

jwt_private_key.pem:

-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMaGKPtS1lTvrkvy
FQ73t7uHjBMKP(...other encoded data)
-----END PRIVATE KEY-----

To generate new RSA256 key in Java use code:

KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();

PrivateKey privateKey = keyPair.getPrivate();
PublicKey privateKey = keyPair.getPublic();
//this is example, not best practics to use
public String generate(User user) throws TokenServiceException {
try {
PrivateKey privateKey = PemKeyUtils.privateKeyFromString(Files.readString(Paths.get("jwt_private_key.pem")));
Date date = Date.from(LocalDateTime.now().plusHours(12).atZone(ZoneId.systemDefault()).toInstant());
return Jwts.builder()
.setSubject(user.getUsername()) // username is "login"
.setExpiration(date)
.signWith(SignatureAlgorithm.RS256, privateKey)
.compact();
} catch (NoSuchAlgorithmException | IOException | InvalidKeySpecException e) {
throw new TokenServiceException(e);
}
}
//output
//yJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJsb2dpbiIsImV4cCI6MTYxNDgwOTQ4OH0.V6OqVCgDT1OpLIPyoX4AU7kFxoYEnF-6becZCSCjszhu6kYXqVVsPbYjBvZNszmv_UJALP7ZMs9hRjL94FZYAfJm0rVJhGioLsU6Tz31oKEZ4xG4D8SvymARECWUe2vPHa3JH8D3WFnUXRU2xrS4esdPLorWTSjb6SD_BpOuQp4
public String validate(String token) throws TokenServiceException {
try {
PublicKey publicKey = PemKeyUtils.publicKeyFromString(Files.readString(Paths.get("jwt_public_key.pem")));
return Jwts.parser()
.setSigningKey(publicKey)
.parseClaimsJws(token)
.getBody()
.getSubject();
} catch (NoSuchAlgorithmException | IOException | InvalidKeySpecException e) {
throw new TokenServiceException(e);
}
}
//output
//login
package com.example.security;
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;
import java.util.Base64;
public class PemKeyUtils {
public static PrivateKey privateKeyFromString(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
privateKey = privateKey.replaceAll("\\n", "")
.replace("-----BEGIN PRIVATE KEY-----", "")
.replace("-----END PRIVATE KEY-----", "")
.replaceAll(" ", "");
return KeyFactory.getInstance("RSA")
.generatePrivate(
new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey))
);
}
public static PublicKey publicKeyFromString(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
publicKey = publicKey.replaceAll("\\n", "")
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replaceAll(" ", "");
return KeyFactory.getInstance("RSA")
.generatePublic(
new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey))
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment