Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Build public key once on Jwk #195

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions src/main/java/com/auth0/jwk/Jwk.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ public class Jwk {
private final String certificateThumbprint;
private final Map<String, Object> additionalAttributes;

private PublicKey publicKey;

/**
* Creates a new Jwk
*
Expand Down Expand Up @@ -174,15 +176,20 @@ public Map<String, Object> getAdditionalAttributes() {
*/
@SuppressWarnings("WeakerAccess")
public PublicKey getPublicKey() throws InvalidPublicKeyException {
PublicKey publicKey = null;
if (publicKey == null) {
buildPublicKey();
}
return publicKey;
}

private void buildPublicKey() throws InvalidPublicKeyException {
switch (type) {
case ALGORITHM_RSA:
try {
KeyFactory kf = KeyFactory.getInstance(ALGORITHM_RSA);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
BigInteger modulus = new BigInteger(1, Base64.getUrlDecoder().decode(stringValue("n")));
BigInteger exponent = new BigInteger(1, Base64.getUrlDecoder().decode(stringValue("e")));
publicKey = kf.generatePublic(new RSAPublicKeySpec(modulus, exponent));
publicKey = keyFactory.generatePublic(new RSAPublicKeySpec(modulus, exponent));
} catch (InvalidKeySpecException e) {
throw new InvalidPublicKeyException("Invalid public key", e);
} catch (NoSuchAlgorithmException e) {
Expand All @@ -194,7 +201,7 @@ public PublicKey getPublicKey() throws InvalidPublicKeyException {
try {
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_ELLIPTIC_CURVE);
ECPoint ecPoint = new ECPoint(new BigInteger(1, Base64.getUrlDecoder().decode(stringValue("x"))),
new BigInteger(1, Base64.getUrlDecoder().decode(stringValue("y"))));
new BigInteger(1, Base64.getUrlDecoder().decode(stringValue("y"))));
AlgorithmParameters algorithmParameters = AlgorithmParameters.getInstance(ALGORITHM_ELLIPTIC_CURVE);

String curve = stringValue("crv");
Expand Down Expand Up @@ -224,8 +231,6 @@ public PublicKey getPublicKey() throws InvalidPublicKeyException {
default:
throw new InvalidPublicKeyException("The key type of " + type + " is not supported");
}

return publicKey;
}

private String stringValue(String key) {
Expand Down