Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions .baseline/checkstyle/checkstyle.xml
Original file line number Diff line number Diff line change
Expand Up @@ -201,10 +201,6 @@
<property name="separated" value="true"/>
<property name="sortStaticImportsAlphabetically" value="true"/>
</module>
<module name="Indentation"> <!-- Java Style Guide: Block indentation: +4 spaces -->
<property name="arrayInitIndent" value="8"/>
<property name="lineWrappingIndentation" value="8"/>
</module>
<module name="InnerAssignment"/> <!-- Java Coding Guidelines: Inner assignments: Not used -->
<module name="LeftCurly"/> <!-- Java Style Guide: Nonempty blocks: K & R style -->
<module name="LineLength"> <!-- Java Style Guide: No line-wrapping -->
Expand Down Expand Up @@ -472,6 +468,9 @@
<property name="format" value="^_?[a-z][a-zA-Z0-9]+$"/>
<message key="name.invalidPattern" value="Parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="SummaryJavadocCheck"> <!-- Java Coding Guidelines: Javadoc -->
<property name="forbiddenSummaryFragments" value="^@return the *|^This method returns |^A [{]@code [a-zA-Z0-9]+[}]( is a )"/>
</module>

<!-- Stricter checks end -->
</module>
Expand Down
2 changes: 2 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ buildscript {
}

dependencies {
classpath 'com.palantir.javaformat:gradle-palantir-java-format:1.0.1'
classpath 'com.netflix.nebula:gradle-info-plugin:8.4.0'
classpath 'com.github.jengelman.gradle.plugins:shadow:6.0.0'
classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.5'
Expand All @@ -23,6 +24,7 @@ apply plugin: 'com.palantir.baseline'
apply plugin: 'com.palantir.consistent-versions'

allprojects {
apply plugin: 'com.palantir.java-format'
group 'com.palantir.hadoop-crypto2'
version gitVersion()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,13 @@ public Cipher initCipher(int opmode) {
*/
@Override
public Cipher seek(long pos) {
Preconditions.checkState(currentOpmode == Cipher.DECRYPT_MODE || currentOpmode == Cipher.ENCRYPT_MODE,
"Cipher not initialized");
Preconditions.checkState(
currentOpmode == Cipher.DECRYPT_MODE || currentOpmode == Cipher.ENCRYPT_MODE, "Cipher not initialized");
Preconditions.checkArgument(pos >= 0, "Cannot seek to negative position: %s", pos);
Preconditions.checkArgument(pos % BLOCK_SIZE == 0,
"Can only seek AES/CBC cipher to block offset positions every %s bytes", BLOCK_SIZE);
Preconditions.checkArgument(
pos % BLOCK_SIZE == 0,
"Can only seek AES/CBC cipher to block offset positions every %s bytes",
BLOCK_SIZE);
return initCipher(currentOpmode);
}

Expand All @@ -101,5 +103,4 @@ private Cipher getInstance() {
throw Throwables.propagate(e);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ public Cipher initCipher(int opmode) {

@Override
public Cipher seek(long pos) {
Preconditions.checkState(currentOpmode == Cipher.DECRYPT_MODE || currentOpmode == Cipher.ENCRYPT_MODE,
"Cipher not initialized");
Preconditions.checkState(
currentOpmode == Cipher.DECRYPT_MODE || currentOpmode == Cipher.ENCRYPT_MODE, "Cipher not initialized");
Preconditions.checkArgument(pos >= 0, "Cannot seek to negative position: %s", pos);

// Compute the block that the byte 'pos' is located in
Expand Down Expand Up @@ -127,5 +127,4 @@ private Cipher getInstance() {
throw Throwables.propagate(e);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,8 @@ private ApacheCiphers() {}
* Properties)} will only try to use the OpenSSL cipher implementation which uses AES-NI.
*/
public static Properties forceOpenSsl(Properties properties) {
properties.setProperty(CryptoCipherFactory.CLASSES_KEY,
CryptoCipherFactory.CipherProvider.OPENSSL.getClassName());
properties.setProperty(
CryptoCipherFactory.CLASSES_KEY, CryptoCipherFactory.CipherProvider.OPENSSL.getClassName());
return properties;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,4 @@ public interface CipherStreamSupplier {
* encryption.
*/
CipherOutputStream getOutputStream(OutputStream os, Cipher cipher);

}
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,12 @@
public final class CipherStreamSupplierImpl implements CipherStreamSupplier {

@Override
public CipherInputStream getInputStream(InputStream is, Cipher cipher) {
public CipherInputStream getInputStream(InputStream is, Cipher cipher) {
return new CipherInputStream(is, cipher);
}

@Override
public CipherOutputStream getOutputStream(OutputStream os, Cipher cipher) {
return new CipherOutputStream(os, cipher);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -47,5 +47,4 @@ static String getProvider(List<String> providers) {
throw new IllegalStateException(
String.format("None of the acceptable JCE providers are available: %s", providers));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,4 @@ public interface SeekableCipher {
* Returns the underlying {@link Cipher}'s block size.
*/
int getBlockSize();

}
Original file line number Diff line number Diff line change
Expand Up @@ -73,5 +73,4 @@ public static SeekableCipher getCipher(String cipherAlgorithm, KeyMaterial keyMa
String.format("No known SeekableCipher with algorithm: %s", cipherAlgorithm));
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,12 @@ public final class ApacheCtrDecryptingSeekableInput extends CtrCryptoInputStream
* the OpenSSL library is able to be loaded.
*/
ApacheCtrDecryptingSeekableInput(SeekableInput input, KeyMaterial keyMaterial) throws IOException {
super(new InputAdapter(input), Utils.getCipherInstance(ALGORITHM, PROPS), BUFFER_SIZE,
keyMaterial.getSecretKey().getEncoded(), keyMaterial.getIv());
super(
new InputAdapter(input),
Utils.getCipherInstance(ALGORITHM, PROPS),
BUFFER_SIZE,
keyMaterial.getSecretKey().getEncoded(),
keyMaterial.getIv());
}

@Override
Expand Down Expand Up @@ -113,5 +117,4 @@ public void close() throws IOException {
input.close();
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,8 @@ private static OutputStream createApacheEncryptedStream(OutputStream output, Key
return new CtrCryptoOutputStream(PROPS, output, secretKey.getEncoded(), iv);
}

private static OutputStream createDefaultEncryptedStream(OutputStream output, KeyMaterial keyMaterial,
String algorithm) {
private static OutputStream createDefaultEncryptedStream(
OutputStream output, KeyMaterial keyMaterial, String algorithm) {
SeekableCipher cipher = SeekableCipherFactory.getCipher(algorithm, keyMaterial);
return new CipherOutputStream(output, cipher.initCipher(Cipher.ENCRYPT_MODE));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,5 +136,4 @@ public void close() throws IOException {
// is not fixed until Java 7u85 (not publicly available) and Java 8u51.
// decryptedStream.close();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,4 @@ public int read(byte[] bytes, int offset, int length) throws IOException {
public void close() throws IOException {
input.close();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ public final void testSeek() throws BadPaddingException, IllegalBlockSizeExcepti
decryptCipher = seekableCipher.seek(prevBlockOffset);

// Decrypt from block n - 1 to the end of the encrypted data
byte[] lastBlocksData = decryptCipher.doFinal(
encryptedData, prevBlockOffset, encryptedData.length - prevBlockOffset);
byte[] lastBlocksData =
decryptCipher.doFinal(encryptedData, prevBlockOffset, encryptedData.length - prevBlockOffset);
byte[] lastBlockData = Arrays.copyOfRange(lastBlocksData, blockSize, 2 * blockSize);

byte[] expected = new byte[blockSize];
Expand Down Expand Up @@ -129,5 +129,4 @@ public final void testEncryptDecrypt(Cipher encryptingCipher, Cipher decryptingC
assertThat(data).isNotEqualTo(encryptedData);
assertThat(data).isEqualTo(decryptedData);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,4 @@ KeyMaterial generateKeyMaterial() {
SeekableCipher getCipher(KeyMaterial initKeyMaterial) {
return new AesCbcCipher(initKeyMaterial);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,6 @@ public void testEncryptDecrypt_ivIncrementedAsUnsignedInt() throws BadPaddingExc
testEncryptDecrypt(encryptCipher, decryptCipher);
}


@Test
public void testIvOverflow() {
KeyMaterial baseKeyMaterial = generateKeyMaterial();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,5 +52,4 @@ public void testGetCipherInputStream() throws IOException {
public void testGetCipherOutputStream() {
assertThat(supplier.getOutputStream(os, cipher)).isInstanceOf(CipherOutputStream.class);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ public void testProvider_exists() {

@Test
public void testProvider_ignoresUnavailable() {
assertThat(Ciphers.getProvider(ImmutableList.of("Invalid", "SunJCE", "IBMJCE"))).doesNotContain("Invalid");
assertThat(Ciphers.getProvider(ImmutableList.of("Invalid", "SunJCE", "IBMJCE")))
.doesNotContain("Invalid");
}

@Test
Expand All @@ -40,5 +41,4 @@ public void testProvider_noneAvailable() {
.isThrownBy(() -> Ciphers.getProvider(ImmutableList.of("Invalid")))
.withMessage("None of the acceptable JCE providers are available: [Invalid]");
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ public void testDecryptingSeekableInput_doesNotSeekNegatively() throws IOExcepti
SeekableCipher cipher = SeekableCipherFactory.getCipher(AesCtrCipher.ALGORITHM, keyMaterial);

for (int increment = 16; increment < 2048; increment += 16) {
try (DecryptingSeekableInput stream = new DecryptingSeekableInput(
new DisallowNegativeSeeksSeekableInput(), cipher)) {
try (DecryptingSeekableInput stream =
new DecryptingSeekableInput(new DisallowNegativeSeeksSeekableInput(), cipher)) {
for (int i = 0; i < 1024 * 1024; i += increment) {
stream.seek(i);
}
Expand Down Expand Up @@ -66,5 +66,4 @@ public int read(byte[] _bytes, int _offset, int length) throws IOException {
return length;
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -92,5 +92,4 @@ public void testGetCipher_invalidNameKeyMaterial() {
.isThrownBy(() -> SeekableCipherFactory.getCipher("doesnt_exist", keyMaterial))
.withMessage("No known SeekableCipher with algorithm: %s", "doesnt_exist");
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -63,5 +63,4 @@ public void decryptingSeekableInputExample() throws IOException {
decryptedStream.read(readBytes, 0, bytes.length);
assertThat(readBytes).isEqualTo(bytes);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ public void before() {
@Test
public void ensureDefaultIsApache() {
OutputStream encrypted = CryptoStreamFactory.encrypt(null, keyMaterial, AesCtrCipher.ALGORITHM);
SeekableInput decrypted = CryptoStreamFactory.decrypt(
(SeekableInput) null, keyMaterial, AesCtrCipher.ALGORITHM);
SeekableInput decrypted =
CryptoStreamFactory.decrypt((SeekableInput) null, keyMaterial, AesCtrCipher.ALGORITHM);

assertThat(encrypted).isInstanceOf(CtrCryptoOutputStream.class);
assertThat(decrypted).isInstanceOf(CtrCryptoInputStream.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,8 @@ public final void apacheEncrypt(State state) throws IOException {
Properties props = ApacheCiphers.forceOpenSsl(new Properties());

ByteArrayOutputStream baos = new ByteArrayOutputStream();
CtrCryptoOutputStream output = new CtrCryptoOutputStream(
props, baos, state.key.getSecretKey().getEncoded(), state.key.getIv());
CtrCryptoOutputStream output =
new CtrCryptoOutputStream(props, baos, state.key.getSecretKey().getEncoded(), state.key.getIv());

output.write(state.data);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,4 @@ public interface AsyncKeyStorageStrategy {
* Async equivalent of {@link KeyStorageStrategy#remove(String)}.
*/
CompletableFuture<Void> remove(String fileKey);

}
Original file line number Diff line number Diff line change
Expand Up @@ -57,22 +57,27 @@ public CompletableFuture<Void> put(String fileKey, KeyMaterial keyMaterial) {

@Override
public CompletableFuture<KeyMaterial> get(String fileKey) {
return CompletableFuture.supplyAsync(() -> {
List<Exception> suppressedExceptions = new ArrayList<>();
for (AsyncKeyStorageStrategy strategy : strategies) {
try {
return strategy.get(fileKey).join();
} catch (Exception e) {
suppressedExceptions.add(e);
log.info("Failed to get key material using {}", strategy.getClass().getCanonicalName(), e);
}
}
RuntimeException toThrow = new RuntimeException(String.format(
"Unable to get key material using any of the provided strategies: %s",
Collections2.transform(strategies, s -> s.getClass().getCanonicalName())));
suppressedExceptions.forEach(toThrow::addSuppressed);
throw toThrow;
}, executor);
return CompletableFuture.supplyAsync(
() -> {
List<Exception> suppressedExceptions = new ArrayList<>();
for (AsyncKeyStorageStrategy strategy : strategies) {
try {
return strategy.get(fileKey).join();
} catch (Exception e) {
suppressedExceptions.add(e);
log.info(
"Failed to get key material using {}",
strategy.getClass().getCanonicalName(),
e);
}
}
RuntimeException toThrow = new RuntimeException(String.format(
"Unable to get key material using any of the provided strategies: %s",
Collections2.transform(strategies, s -> s.getClass().getCanonicalName())));
suppressedExceptions.forEach(toThrow::addSuppressed);
throw toThrow;
},
executor);
}

@Override
Expand All @@ -81,10 +86,7 @@ public CompletableFuture<Void> remove(String fileKey) {
}

private CompletableFuture<Void> applyToStrategies(Function<AsyncKeyStorageStrategy, CompletableFuture<?>> mapper) {
CompletableFuture[] futures = strategies.stream()
.map(mapper)
.toArray(CompletableFuture[]::new);
CompletableFuture[] futures = strategies.stream().map(mapper).toArray(CompletableFuture[]::new);
return CompletableFuture.allOf(futures);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,15 @@ public KeyMaterial get(String fileKey) {
return strategy.get(fileKey);
} catch (Exception e) {
suppressedExceptions.add(e);
logger.info("Failed to get key material using {}", strategy.getClass().getCanonicalName(), e);
logger.info(
"Failed to get key material using {}",
strategy.getClass().getCanonicalName(),
e);
}
}
RuntimeException toThrow = new RuntimeException(String.format(
"Unable to get key material for '%s' using any of the provided strategies: %s",
fileKey,
Collections2.transform(strategies, s -> s.getClass().getCanonicalName())));
fileKey, Collections2.transform(strategies, s -> s.getClass().getCanonicalName())));
suppressedExceptions.forEach(toThrow::addSuppressed);
throw toThrow;
}
Expand All @@ -77,5 +79,4 @@ public void remove(String fileKey) {
strategy.remove(fileKey);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,12 @@ public DefaultAsyncKeyStorageStrategy(KeyStorageStrategy keys, ExecutorService e

@Override
public CompletableFuture<Void> put(String fileKey, KeyMaterial keyMaterial) {
return CompletableFuture.supplyAsync(() -> {
keys.put(fileKey, keyMaterial);
return null;
}, executor);
return CompletableFuture.supplyAsync(
() -> {
keys.put(fileKey, keyMaterial);
return null;
},
executor);
}

@Override
Expand All @@ -44,10 +46,11 @@ public CompletableFuture<KeyMaterial> get(String fileKey) {

@Override
public CompletableFuture<Void> remove(String fileKey) {
return CompletableFuture.supplyAsync(() -> {
keys.remove(fileKey);
return null;
}, executor);
return CompletableFuture.supplyAsync(
() -> {
keys.remove(fileKey);
return null;
},
executor);
}

}
Loading