GenerateAesKeyCommand extends Command { @VisibleForTesting static void generate(char[] password, Path destination, int keySize, String alias, SecureRandom random) throws Exception { KeyGenerator generator = KeyGenerator.getInstance("AES"); generator.init(keySize, random); SecretKey key = generator.generateKey(); KeyStore keyStore = KeyStore.getInstance("JCEKS"); keyStore.load(null); keyStore.setKeyEntry(alias, key, password, null); try (OutputStream out = Files.newOutputStream(destination)) { keyStore.store(out, password); } } GenerateAesKeyCommand(); @Override void configure(Subparser parser); @Override void run(Bootstrap<?> bootstrap, Namespace namespace);  }
@Test public void testKeyGeneration() throws Exception { char[] password = "CHANGE".toCharArray(); Path destination = Paths.get(temporaryFolder.getRoot().getPath(), "derivation.jceks"); int keySize = 128; String alias = "baseKey"; GenerateAesKeyCommand.generate(password, destination, keySize, alias, new SecureRandom()); assertThat(destination).exists(); KeyStore keyStore = KeyStore.getInstance("JCEKS"); try (InputStream in = Files.newInputStream(destination)) { keyStore.load(in, password); } assertThat(keyStore.isKeyEntry(alias)).isTrue(); Key key = keyStore.getKey(alias, password); assertThat(key).isInstanceOf(SecretKey.class); SecretKey secretKey = (SecretKey) key; assertThat(secretKey.getEncoded()).hasSize(keySize/8); }