From 87b568674fe9d8d5de22aaaf555897e7f8286e5b Mon Sep 17 00:00:00 2001 From: Robert Godfrey Date: Tue, 19 Aug 2014 16:13:22 +0000 Subject: QPID-6017 : [Java Broker] add tests for AESKeyFileEncrypterFactory git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk@1618892 13f79535-47bb-0310-9956-ffa450edef68 --- .../encryption/AESKeyFileEncrypterFactory.java | 12 +- .../security/encryption/AESFileEncrypterTest.java | 194 ------------- .../encryption/AESKeyFileEncrypterFactoryTest.java | 313 +++++++++++++++++++++ .../encryption/AESKeyFileEncrypterTest.java | 194 +++++++++++++ 4 files changed, 514 insertions(+), 199 deletions(-) delete mode 100644 qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/encryption/AESFileEncrypterTest.java create mode 100644 qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/encryption/AESKeyFileEncrypterFactoryTest.java create mode 100644 qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/encryption/AESKeyFileEncrypterTest.java (limited to 'qpid/java') diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/encryption/AESKeyFileEncrypterFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/encryption/AESKeyFileEncrypterFactory.java index 7a4394de1e..ef92c2a131 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/encryption/AESKeyFileEncrypterFactory.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/encryption/AESKeyFileEncrypterFactory.java @@ -46,7 +46,7 @@ import org.apache.qpid.server.plugin.PluggableService; @PluggableService public class AESKeyFileEncrypterFactory implements ConfigurationSecretEncrypterFactory { - private static final String ENCRYPTER_KEY_FILE = "encrypter.key.file"; + static final String ENCRYPTER_KEY_FILE = "encrypter.key.file"; private static final int AES_KEY_SIZE_BITS = 256; private static final int AES_KEY_SIZE_BYTES = AES_KEY_SIZE_BITS / 8; @@ -54,6 +54,8 @@ public class AESKeyFileEncrypterFactory implements ConfigurationSecretEncrypterF public static final String TYPE = "AESKeyFile"; + static final String DEFAULT_KEYS_SUBDIR_NAME = ".keys"; + @Override public ConfigurationSecretEncrypter createEncrypter(final ConfiguredObject object) { @@ -66,7 +68,7 @@ public class AESKeyFileEncrypterFactory implements ConfigurationSecretEncrypterF { fileLocation = object.getContextValue(String.class, BrokerOptions.QPID_WORK_DIR) - + File.separator + ".keys" + File.separator + + File.separator + DEFAULT_KEYS_SUBDIR_NAME + File.separator + object.getCategoryClass().getSimpleName() + "_" + object.getName() + ".key"; @@ -94,14 +96,14 @@ public class AESKeyFileEncrypterFactory implements ConfigurationSecretEncrypterF || permissions.contains(PosixFilePermission.GROUP_WRITE) || permissions.contains(PosixFilePermission.OTHERS_WRITE)) { - throw new IllegalStateException("Key file '" + throw new IllegalArgumentException("Key file '" + fileLocation + "' has incorrect permissions. Only the owner " + "should be able to read or write this file."); } if(Files.size(file.toPath()) != AES_KEY_SIZE_BYTES) { - throw new IllegalConfigurationException("Key file '" + fileLocation + "' contains an incorrect about of data"); + throw new IllegalArgumentException("Key file '" + fileLocation + "' contains an incorrect about of data"); } try(FileInputStream inputStream = new FileInputStream(file)) @@ -151,7 +153,7 @@ public class AESKeyFileEncrypterFactory implements ConfigurationSecretEncrypterF } catch (NoSuchAlgorithmException | IOException e) { - throw new IllegalConfigurationException("Cannot create key file: " + e.getMessage(), e); + throw new IllegalArgumentException("Cannot create key file: " + e.getMessage(), e); } } diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/encryption/AESFileEncrypterTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/encryption/AESFileEncrypterTest.java deleted file mode 100644 index 4105924507..0000000000 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/encryption/AESFileEncrypterTest.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.encryption; - -import java.nio.charset.StandardCharsets; -import java.security.SecureRandom; -import java.util.HashSet; -import java.util.Random; -import java.util.Set; - -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.PBEKeySpec; -import javax.crypto.spec.SecretKeySpec; - -import org.apache.qpid.test.utils.QpidTestCase; - -public class AESFileEncrypterTest extends QpidTestCase -{ - private final SecureRandom _random = new SecureRandom(); - public static final String PLAINTEXT = "notaverygoodpassword"; - - public void testSimpleEncryptDecrypt() throws Exception - { - doTestSimpleEncryptDecrypt(PLAINTEXT); - } - - - public void testRepeatedEncryptionsReturnDifferentValues() - { - SecretKeySpec secretKey = createSecretKey(); - AESKeyFileEncrypter encrypter = new AESKeyFileEncrypter(secretKey); - - Set encryptions = new HashSet<>(); - - int iterations = 100; - - for(int i = 0; i < iterations; i++) - { - encryptions.add(encrypter.encrypt(PLAINTEXT)); - } - - assertEquals("Not all encryptions were distinct", iterations, encryptions.size()); - - for(String encrypted : encryptions) - { - assertEquals("Not all encryptions decrypt correctly", PLAINTEXT, encrypter.decrypt(encrypted)); - } - } - - public void testCreationFailsOnInvalidSecret() throws Exception - { - try - { - new AESKeyFileEncrypter(null); - fail("An encrypter should not be creatable from a null key"); - } - catch(NullPointerException e) - { - // pass - } - - try - { - PBEKeySpec keySpec = new PBEKeySpec("password".toCharArray()); - SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); - new AESKeyFileEncrypter(factory.generateSecret(keySpec)); - fail("An encrypter should not be creatable from the wrong type of secret key"); - } - catch (IllegalArgumentException e) - { - // pass - } - } - - public void testEncryptionOfEmptyString() - { - String text = ""; - doTestSimpleEncryptDecrypt(text); - } - - private void doTestSimpleEncryptDecrypt(final String text) - { - SecretKeySpec secretKey = createSecretKey(); - AESKeyFileEncrypter encrypter = new AESKeyFileEncrypter(secretKey); - - String encrypted = encrypter.encrypt(text); - assertNotNull("Encrypter did not return a result from encryption", encrypted); - assertFalse("Plain text and encrypted version are equal", text.equals(encrypted)); - String decrypted = encrypter.decrypt(encrypted); - assertNotNull("Encrypter did not return a result from decryption",decrypted); - assertTrue("Encryption was not reversible", text.equals(decrypted)); - } - - public void testEncryptingNullFails() - { - try - { - SecretKeySpec secretKey = createSecretKey(); - AESKeyFileEncrypter encrypter = new AESKeyFileEncrypter(secretKey); - - String encrypted = encrypter.encrypt(null); - fail("Attempting to encrypt null should fail"); - } - catch(NullPointerException e) - { - // pass - } - } - - public void testEncryptingVeryLargeSecret() - { - Random random = new Random(); - byte[] data = new byte[4096]; - random.nextBytes(data); - for(int i = 0; i < data.length; i++) - { - data[i] = (byte)(data[i] & 0xEF); - } - doTestSimpleEncryptDecrypt(new String(data, StandardCharsets.US_ASCII)); - } - - public void testDecryptNonsense() - { - - SecretKeySpec secretKey = createSecretKey(); - AESKeyFileEncrypter encrypter = new AESKeyFileEncrypter(secretKey); - - - try - { - encrypter.decrypt(null); - fail("Should not decrypt a null value"); - } - catch(NullPointerException e) - { - // pass - } - - try - { - encrypter.decrypt(""); - fail("Should not decrypt the empty String"); - } - catch(IllegalArgumentException e) - { - // pass - } - - try - { - encrypter.decrypt("thisisnonsense"); - fail("Should not decrypt a small amount of nonsense"); - } - catch(IllegalArgumentException e) - { - // pass - } - - try - { - String answer = encrypter.decrypt("thisisn'tvalidBase64!soitshouldfailwithanIllegalArgumentException"); - fail("Should not decrypt a larger amount of nonsense"); - } - catch(IllegalArgumentException e) - { - // pass - } - } - - private SecretKeySpec createSecretKey() - { - final byte[] keyData = new byte[32]; - _random.nextBytes(keyData); - return new SecretKeySpec(keyData, "AES"); - } -} diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/encryption/AESKeyFileEncrypterFactoryTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/encryption/AESKeyFileEncrypterFactoryTest.java new file mode 100644 index 0000000000..0d71f66cc2 --- /dev/null +++ b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/encryption/AESKeyFileEncrypterFactoryTest.java @@ -0,0 +1,313 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.security.encryption; + +import static org.mockito.Matchers.anyMap; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.util.Collections; +import java.util.EnumSet; +import java.util.Map; +import java.util.UUID; + +import org.mockito.ArgumentCaptor; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import org.apache.qpid.server.BrokerOptions; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.test.utils.QpidTestCase; + +public class AESKeyFileEncrypterFactoryTest extends QpidTestCase +{ + private Broker _broker; + private Path _tmpDir; + private AESKeyFileEncrypterFactory _factory; + + @Override + public void setUp() throws Exception + { + super.setUp(); + _broker = mock(Broker.class); + _tmpDir = Files.createTempDirectory(getTestName()); + + when(_broker.getContextKeys(eq(false))).thenReturn(Collections.emptySet()); + when(_broker.getContextValue(eq(String.class), eq(BrokerOptions.QPID_WORK_DIR))).thenReturn(_tmpDir.toString()); + when(_broker.getCategoryClass()).thenReturn(Broker.class); + when(_broker.getName()).thenReturn(getName()); + final ArgumentCaptor contextCaptor = ArgumentCaptor.forClass(Map.class); + + when(_broker.setAttribute(eq("context"), anyMap(), contextCaptor.capture() )).thenAnswer(new Answer() { + + @Override + public Void answer(final InvocationOnMock invocationOnMock) throws Throwable + { + Map replacementContext = contextCaptor.getValue(); + when(_broker.getContext()).thenReturn(replacementContext); + return null; + } + }); + + _factory = new AESKeyFileEncrypterFactory(); + } + + public void testCreateKeyInDefaultLocation() throws Exception + { + ConfigurationSecretEncrypter encrypter = _factory.createEncrypter(_broker); + + KeyFilePathChecker keyFilePathChecker = new KeyFilePathChecker(); + + doChecks(encrypter, keyFilePathChecker); + + String pathName = (String) _broker.getContext().get(AESKeyFileEncrypterFactory.ENCRYPTER_KEY_FILE); + + // check the context variable was set + assertEquals(keyFilePathChecker.getKeyFile().toString(), pathName); + } + + private void doChecks(final ConfigurationSecretEncrypter encrypter, + final KeyFilePathChecker keyFilePathChecker) throws IOException + { + // walk the directory to find the file + Files.walkFileTree(_tmpDir, keyFilePathChecker); + + // check the file was actually found + assertNotNull(keyFilePathChecker.getKeyFile()); + + String secret = "notasecret"; + + // check the encrypter works + assertEquals(secret, encrypter.decrypt(encrypter.encrypt(secret))); + + } + + public void testSettingContextKeyLeadsToFileCreation() throws Exception + { + String filename = UUID.randomUUID().toString() + ".key"; + String subdirName = getTestName() + File.separator + "test"; + String fileLocation = _tmpDir.toString() + File.separator + subdirName + File.separator + filename; + + when(_broker.getContextKeys(eq(false))).thenReturn(Collections.singleton(AESKeyFileEncrypterFactory.ENCRYPTER_KEY_FILE)); + when(_broker.getContextValue(eq(String.class), eq(AESKeyFileEncrypterFactory.ENCRYPTER_KEY_FILE))).thenReturn(fileLocation); + + ConfigurationSecretEncrypter encrypter = _factory.createEncrypter(_broker); + + KeyFilePathChecker keyFilePathChecker = new KeyFilePathChecker(subdirName, filename); + + doChecks(encrypter, keyFilePathChecker); + + } + + + public void testUnableToCreateFileInSpecifiedLocation() throws Exception + { + String filename = UUID.randomUUID().toString() + ".key"; + String subdirName = getTestName() + File.separator + "test"; + String fileLocation = _tmpDir.toString() + File.separator + subdirName + File.separator + filename; + + when(_broker.getContextKeys(eq(false))).thenReturn(Collections.singleton(AESKeyFileEncrypterFactory.ENCRYPTER_KEY_FILE)); + when(_broker.getContextValue(eq(String.class), eq(AESKeyFileEncrypterFactory.ENCRYPTER_KEY_FILE))).thenReturn(fileLocation); + + Files.createDirectories(Paths.get(fileLocation)); + + try + { + ConfigurationSecretEncrypter encrypter = _factory.createEncrypter(_broker); + fail("should not be able to create a key file where a directory currently is"); + } + catch(IllegalArgumentException e) + { + // pass + } + } + + + public void testPermissionsAreChecked() throws Exception + { + String filename = UUID.randomUUID().toString() + ".key"; + String subdirName = getTestName() + File.separator + "test"; + String fileLocation = _tmpDir.toString() + File.separator + subdirName + File.separator + filename; + + when(_broker.getContextKeys(eq(false))).thenReturn(Collections.singleton(AESKeyFileEncrypterFactory.ENCRYPTER_KEY_FILE)); + when(_broker.getContextValue(eq(String.class), eq(AESKeyFileEncrypterFactory.ENCRYPTER_KEY_FILE))).thenReturn(fileLocation); + + Files.createDirectories(Paths.get(_tmpDir.toString(), subdirName)); + + File file = new File(fileLocation); + file.createNewFile(); + Files.setPosixFilePermissions(file.toPath(), EnumSet.of(PosixFilePermission.OWNER_READ,PosixFilePermission.GROUP_READ)); + + try + { + ConfigurationSecretEncrypter encrypter = _factory.createEncrypter(_broker); + fail("should not be able to create a key file where the file is readable"); + } + catch(IllegalArgumentException e) + { + // pass + } + } + + public void testInvalidKey() throws Exception + { + String filename = UUID.randomUUID().toString() + ".key"; + String subdirName = getTestName() + File.separator + "test"; + String fileLocation = _tmpDir.toString() + File.separator + subdirName + File.separator + filename; + + when(_broker.getContextKeys(eq(false))).thenReturn(Collections.singleton(AESKeyFileEncrypterFactory.ENCRYPTER_KEY_FILE)); + when(_broker.getContextValue(eq(String.class), eq(AESKeyFileEncrypterFactory.ENCRYPTER_KEY_FILE))).thenReturn(fileLocation); + + Files.createDirectories(Paths.get(_tmpDir.toString(), subdirName)); + + File file = new File(fileLocation); + try(FileOutputStream fos = new FileOutputStream(file)) + { + fos.write("This is not an AES key. It is a string saying it is not an AES key".getBytes(StandardCharsets.US_ASCII)); + } + Files.setPosixFilePermissions(file.toPath(), EnumSet.of(PosixFilePermission.OWNER_READ)); + + try + { + ConfigurationSecretEncrypter encrypter = _factory.createEncrypter(_broker); + fail("should not be able to start where the key is not a valid key"); + } + catch(IllegalArgumentException e) + { + // pass + } + } + + @Override + public void tearDown() throws Exception + { + Files.walkFileTree(_tmpDir, + new SimpleFileVisitor() + { + @Override + public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) + throws IOException + { + Files.delete(file); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) + throws IOException + { + Files.delete(dir); + return FileVisitResult.CONTINUE; + } + }); + super.tearDown(); + } + + private class KeyFilePathChecker extends SimpleFileVisitor + { + + private final String _fileName; + private final String _subdirName; + private Path _keyFile; + private boolean _inKeysSubdir; + + public KeyFilePathChecker() + { + this(AESKeyFileEncrypterFactory.DEFAULT_KEYS_SUBDIR_NAME, "Broker_" + AESKeyFileEncrypterFactoryTest.this.getName() + ".key"); + } + + public KeyFilePathChecker(final String subdirName, final String fileName) + { + _subdirName = subdirName; + _fileName = fileName; + } + + @Override + public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException + { + if(!_inKeysSubdir && dir.endsWith(_subdirName)) + { + _inKeysSubdir = true; + assertFalse(Files.getPosixFilePermissions(dir).contains(PosixFilePermission.OTHERS_READ)); + assertFalse(Files.getPosixFilePermissions(dir).contains(PosixFilePermission.OTHERS_WRITE)); + assertFalse(Files.getPosixFilePermissions(dir).contains(PosixFilePermission.OTHERS_EXECUTE)); + + assertFalse(Files.getPosixFilePermissions(dir).contains(PosixFilePermission.GROUP_READ)); + assertFalse(Files.getPosixFilePermissions(dir).contains(PosixFilePermission.GROUP_WRITE)); + assertFalse(Files.getPosixFilePermissions(dir).contains(PosixFilePermission.GROUP_EXECUTE)); + return FileVisitResult.CONTINUE; + } + else + { + return _inKeysSubdir ? FileVisitResult.SKIP_SUBTREE : FileVisitResult.CONTINUE; + } + + } + + @Override + public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException + { + if(_inKeysSubdir) + { + if(file.endsWith(_fileName)) + { + _keyFile = file; + + assertFalse(Files.getPosixFilePermissions(file).contains(PosixFilePermission.OTHERS_READ)); + assertFalse(Files.getPosixFilePermissions(file).contains(PosixFilePermission.OTHERS_WRITE)); + assertFalse(Files.getPosixFilePermissions(file).contains(PosixFilePermission.OTHERS_EXECUTE)); + + assertFalse(Files.getPosixFilePermissions(file).contains(PosixFilePermission.GROUP_READ)); + assertFalse(Files.getPosixFilePermissions(file).contains(PosixFilePermission.GROUP_WRITE)); + assertFalse(Files.getPosixFilePermissions(file).contains(PosixFilePermission.GROUP_EXECUTE)); + + return FileVisitResult.TERMINATE; + } + } + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException + { + _inKeysSubdir = false; + return FileVisitResult.CONTINUE; + } + + public Path getKeyFile() + { + return _keyFile; + } + + } +} diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/encryption/AESKeyFileEncrypterTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/encryption/AESKeyFileEncrypterTest.java new file mode 100644 index 0000000000..b08c32a4f2 --- /dev/null +++ b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/encryption/AESKeyFileEncrypterTest.java @@ -0,0 +1,194 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.security.encryption; + +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.util.HashSet; +import java.util.Random; +import java.util.Set; + +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.SecretKeySpec; + +import org.apache.qpid.test.utils.QpidTestCase; + +public class AESKeyFileEncrypterTest extends QpidTestCase +{ + private final SecureRandom _random = new SecureRandom(); + public static final String PLAINTEXT = "notaverygoodpassword"; + + public void testSimpleEncryptDecrypt() throws Exception + { + doTestSimpleEncryptDecrypt(PLAINTEXT); + } + + + public void testRepeatedEncryptionsReturnDifferentValues() + { + SecretKeySpec secretKey = createSecretKey(); + AESKeyFileEncrypter encrypter = new AESKeyFileEncrypter(secretKey); + + Set encryptions = new HashSet<>(); + + int iterations = 100; + + for(int i = 0; i < iterations; i++) + { + encryptions.add(encrypter.encrypt(PLAINTEXT)); + } + + assertEquals("Not all encryptions were distinct", iterations, encryptions.size()); + + for(String encrypted : encryptions) + { + assertEquals("Not all encryptions decrypt correctly", PLAINTEXT, encrypter.decrypt(encrypted)); + } + } + + public void testCreationFailsOnInvalidSecret() throws Exception + { + try + { + new AESKeyFileEncrypter(null); + fail("An encrypter should not be creatable from a null key"); + } + catch(NullPointerException e) + { + // pass + } + + try + { + PBEKeySpec keySpec = new PBEKeySpec("password".toCharArray()); + SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); + new AESKeyFileEncrypter(factory.generateSecret(keySpec)); + fail("An encrypter should not be creatable from the wrong type of secret key"); + } + catch (IllegalArgumentException e) + { + // pass + } + } + + public void testEncryptionOfEmptyString() + { + String text = ""; + doTestSimpleEncryptDecrypt(text); + } + + private void doTestSimpleEncryptDecrypt(final String text) + { + SecretKeySpec secretKey = createSecretKey(); + AESKeyFileEncrypter encrypter = new AESKeyFileEncrypter(secretKey); + + String encrypted = encrypter.encrypt(text); + assertNotNull("Encrypter did not return a result from encryption", encrypted); + assertFalse("Plain text and encrypted version are equal", text.equals(encrypted)); + String decrypted = encrypter.decrypt(encrypted); + assertNotNull("Encrypter did not return a result from decryption",decrypted); + assertTrue("Encryption was not reversible", text.equals(decrypted)); + } + + public void testEncryptingNullFails() + { + try + { + SecretKeySpec secretKey = createSecretKey(); + AESKeyFileEncrypter encrypter = new AESKeyFileEncrypter(secretKey); + + String encrypted = encrypter.encrypt(null); + fail("Attempting to encrypt null should fail"); + } + catch(NullPointerException e) + { + // pass + } + } + + public void testEncryptingVeryLargeSecret() + { + Random random = new Random(); + byte[] data = new byte[4096]; + random.nextBytes(data); + for(int i = 0; i < data.length; i++) + { + data[i] = (byte)(data[i] & 0xEF); + } + doTestSimpleEncryptDecrypt(new String(data, StandardCharsets.US_ASCII)); + } + + public void testDecryptNonsense() + { + + SecretKeySpec secretKey = createSecretKey(); + AESKeyFileEncrypter encrypter = new AESKeyFileEncrypter(secretKey); + + + try + { + encrypter.decrypt(null); + fail("Should not decrypt a null value"); + } + catch(NullPointerException e) + { + // pass + } + + try + { + encrypter.decrypt(""); + fail("Should not decrypt the empty String"); + } + catch(IllegalArgumentException e) + { + // pass + } + + try + { + encrypter.decrypt("thisisnonsense"); + fail("Should not decrypt a small amount of nonsense"); + } + catch(IllegalArgumentException e) + { + // pass + } + + try + { + String answer = encrypter.decrypt("thisisn'tvalidBase64!soitshouldfailwithanIllegalArgumentException"); + fail("Should not decrypt a larger amount of nonsense"); + } + catch(IllegalArgumentException e) + { + // pass + } + } + + private SecretKeySpec createSecretKey() + { + final byte[] keyData = new byte[32]; + _random.nextBytes(keyData); + return new SecretKeySpec(keyData, "AES"); + } +} -- cgit v1.2.1