Skip to content

Commit

Permalink
Added validateKey tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ianaz committed Jan 15, 2025
1 parent 0316b5b commit 7b4549e
Showing 1 changed file with 27 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import org.junit.jupiter.api.BeforeEach;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import uk.org.webcompere.systemstubs.environment.EnvironmentVariables;
Expand All @@ -11,6 +13,7 @@

import java.security.NoSuchAlgorithmException;

import static my.unifi.eset.keycloak.piidataencryption.utils.EncryptionUtils.algorithm;
import static org.junit.jupiter.api.Assertions.*;

@ExtendWith(SystemStubsExtension.class)
Expand Down Expand Up @@ -55,10 +58,32 @@ void testWrongKeySize() {
EncryptionUtils.getEncryptionKey();
});

assertEquals("Invalid encryption key for algorithm AES/CBC/PKCS5Padding", thrown.getMessage());
assertEquals("Invalid encryption key for algorithm " + algorithm, thrown.getMessage());


environmentVariables.set(envVarKey, validEncKey);
assertDoesNotThrow(() -> EncryptionUtils.getEncryptionKey(), "should work once the key is correct and not reuse the previous one");
}
}

@Test
void testValidKey() {
byte[] validKeyBytes = validEncKey.getBytes();
SecretKeySpec validKey = new SecretKeySpec(validKeyBytes, "AES");

assertDoesNotThrow(() -> EncryptionUtils.validateKey(validKey));
}

@Test
void testValidateAnInvalidKey() {
byte[] invalidKeyBytes = "invalid_size".getBytes();
SecretKeySpec invalidKey = new SecretKeySpec(invalidKeyBytes, "AES");

IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> {
EncryptionUtils.validateKey(invalidKey);
});

String expectedMessage = "Invalid encryption key for algorithm " + algorithm;
assertThrows(IllegalArgumentException.class, () -> EncryptionUtils.validateKey(invalidKey));
assert(thrown.getMessage().contains(expectedMessage));
}
}

0 comments on commit 7b4549e

Please sign in to comment.