LazySecretKeyImpl implements LazySecretKey { @Override public SecretKey getOrCreate() throws Exception { synchronized (lock) { if (secretKey == null) { File secretFile = getSecretFile(confDirs); if (secretFile == null) { secretFile = new File(confDirs.get(0), SECRET_FILE_NAME); secretKey = Encryption.generateNewKey(); Files.write(secretKey.getEncoded(), secretFile); } else { secretKey = loadKey(secretFile); } } return secretKey; } } LazySecretKeyImpl(List<File> confDirs); @Override @Nullable SecretKey getExisting(); @Override SecretKey getOrCreate();  }
@Test public void testLoadSecretKey() throws Exception { SecretKey secretKey = Encryption.generateNewKey(); File confDir = Files.createTempDir(); File secretKeyFile = new File(confDir, "secret"); byte[] encodedKey = secretKey.getEncoded(); Files.write(encodedKey, secretKeyFile); LazySecretKey lazySecretKey = new LazySecretKeyImpl(Arrays.asList(confDir)); assertThat(lazySecretKey.getOrCreate().getEncoded()).isEqualTo(encodedKey); secretKeyFile.delete(); confDir.delete(); }