Skip to content

Commit

Permalink
Fix NPE when key null and using JWT tokens with RS256 or ES256 algori…
Browse files Browse the repository at this point in the history
…thms(#59)

thanks to @DolphFlynn
  • Loading branch information
DolphFlynn committed Jan 7, 2022
1 parent 80198fa commit 6d02b00
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
4 changes: 3 additions & 1 deletion src/app/algorithm/AlgorithmLinker.java
Expand Up @@ -19,6 +19,8 @@
import app.helpers.KeyHelper;
import app.helpers.Output;

import static org.apache.commons.lang.StringUtils.isNotEmpty;

public class AlgorithmLinker {

public static final String[] keyBeginMarkers = new String[]{"-----BEGIN PUBLIC KEY-----",
Expand Down Expand Up @@ -53,7 +55,7 @@ public class AlgorithmLinker {

private static PublicKey generatePublicKeyFromString(String key, String algorithm) {
PublicKey publicKey = null;
if (key.length() > 1) {
if (isNotEmpty(key)) {
key = cleanKey(key);
byte[] keyByteArray = java.util.Base64.getDecoder().decode(key);
try {
Expand Down
4 changes: 3 additions & 1 deletion src/app/helpers/KeyHelper.java
Expand Up @@ -16,6 +16,8 @@
import app.algorithm.AlgorithmLinker;
import app.algorithm.AlgorithmType;

import static org.apache.commons.lang.StringUtils.isNotEmpty;

public class KeyHelper {

public static final String[] keyHeaderBeginMarkers = new String[]{"-----BEGIN PUBLIC KEY-----",
Expand Down Expand Up @@ -52,7 +54,7 @@ public static String getRandomKey(String algorithm) {

public static PrivateKey generatePrivateKeyFromString(String key, String algorithm) {
PrivateKey privateKey = null;
if (key.length() > 1) {
if (isNotEmpty(key)) {
key = cleanKey(key);
try {
byte[] keyByteArray = Base64.decodeBase64(key);
Expand Down
31 changes: 31 additions & 0 deletions test/app/TestAlgorithmLinker.java
@@ -1,6 +1,7 @@
package app;

import java.io.UnsupportedEncodingException;
import java.security.Key;

import org.junit.Test;

Expand All @@ -11,6 +12,8 @@
import app.algorithm.AlgorithmLinker;
import model.CustomJWToken;

import static org.junit.Assert.assertNull;

public class TestAlgorithmLinker {

@Test
Expand Down Expand Up @@ -44,4 +47,32 @@ public void testESWithFalseKey() throws IllegalArgumentException, UnsupportedEnc
DecodedJWT test = verifier.verify(TestTokens.es256_token);
test.getAlgorithm();
}

@Test
public void testGetKeyInstanceWithNullKeyForPublicRSA() {
Key key = AlgorithmLinker.getKeyInstance(null, "RSA", false);

assertNull(key);
}

@Test
public void testGetKeyInstanceWithNullKeyForPublicEC() {
Key key = AlgorithmLinker.getKeyInstance(null, "EC", false);

assertNull(key);
}

@Test
public void testGetKeyInstanceWithNullKeyForPrivateRSA() {
Key key = AlgorithmLinker.getKeyInstance(null, "RSA", true);

assertNull(key);
}

@Test
public void testGetKeyInstanceWithNullKeyForPrivateEC() {
Key key = AlgorithmLinker.getKeyInstance(null, "EC", true);

assertNull(key);
}
}

0 comments on commit 6d02b00

Please sign in to comment.