index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/PigPen/pigpen-cascading/src/main/java/pigpen | Create_ds/PigPen/pigpen-cascading/src/main/java/pigpen/cascading/ReduceBuffer.java | /*
*
* Copyright 2015 Netflix, Inc.
*
* Licensed 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 pigpen.cascading;
import cascading.flow.FlowProcess;
import cascading.operation.BaseOperation;
import cascading.operation.Buffer;
import cascading.operation.BufferCall;
import cascading.operation.OperationCall;
import cascading.tuple.Fields;
import clojure.lang.IFn;
public class ReduceBuffer extends BaseOperation implements Buffer {
private static final IFn PREPARE = OperationUtil.getVar("prepare");
private static final IFn OPERATE = OperationUtil.getVar("reduce-operate");
private final String context;
public ReduceBuffer(final String context, final Fields fields) {
super(fields);
this.context = context;
}
@Override
public void prepare(final FlowProcess flowProcess, final OperationCall operationCall) {
super.prepare(flowProcess, operationCall);
operationCall.setContext(PREPARE.invoke(this.context));
}
@Override
public void operate(final FlowProcess flowProcess, final BufferCall bufferCall) {
OPERATE.invoke(bufferCall);
}
}
| 2,200 |
0 | Create_ds/PigPen/pigpen-cascading/src/main/java/pigpen | Create_ds/PigPen/pigpen-cascading/src/main/java/pigpen/cascading/PigPenAggregateBy.java | /*
*
* Copyright 2015 Netflix, Inc.
*
* Licensed 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 pigpen.cascading;
import cascading.flow.FlowProcess;
import cascading.operation.Aggregator;
import cascading.operation.AggregatorCall;
import cascading.operation.BaseOperation;
import cascading.pipe.Pipe;
import cascading.pipe.assembly.AggregateBy;
import cascading.tuple.Fields;
import cascading.tuple.Tuple;
import cascading.tuple.TupleEntry;
import clojure.lang.IFn;
public class PigPenAggregateBy extends AggregateBy {
public PigPenAggregateBy(final String context, final Pipe pipe, final Fields groupingFields, final Fields argFields) {
super(null, new Pipe[] { pipe }, groupingFields, argFields, new Partial(context, argFields), new Final(context, argFields), 0);
}
private static class Partial implements Functor {
private static final IFn PREPARE = OperationUtil.getVar("prepare");
private static final IFn AGGREGATE = OperationUtil.getVar("aggregate-partial-aggregate");
private static final IFn COMPLETE = OperationUtil.getVar("aggregate-partial-complete");
private final String context;
private final Fields fields;
public Partial(final String context, final Fields fields) {
this.context = context;
this.fields = fields;
}
@Override
public Fields getDeclaredFields() {
return this.fields;
}
@Override
public Tuple aggregate(final FlowProcess flowProcess, final TupleEntry args, final Tuple agg) {
return new Tuple(AGGREGATE.invoke(PREPARE.invoke(this.context), args, agg));
}
@Override
public Tuple complete(final FlowProcess flowProcess, final Tuple agg) {
return (Tuple) COMPLETE.invoke(agg);
}
}
public static class Final extends BaseOperation implements Aggregator {
private static final IFn PREPARE = OperationUtil.getVar("prepare");
private static final IFn START = OperationUtil.getVar("aggregate-final-start");
private static final IFn AGGREGATE = OperationUtil.getVar("aggregate-final-aggregate");
private static final IFn COMPLETE = OperationUtil.getVar("aggregate-final-complete");
private final String context;
public Final(final String context, final Fields fields) {
super(fields);
this.context = context;
}
@Override
public void start(final FlowProcess flowProcess, final AggregatorCall aggregatorCall) {
aggregatorCall.setContext(START.invoke(PREPARE.invoke(this.context), aggregatorCall));
}
@Override
public void aggregate(final FlowProcess flowProcess, final AggregatorCall aggregatorCall) {
aggregatorCall.setContext(AGGREGATE.invoke(PREPARE.invoke(this.context), aggregatorCall));
}
@Override
public void complete(final FlowProcess flowProcess, final AggregatorCall aggregatorCall) {
COMPLETE.invoke(PREPARE.invoke(this.context), aggregatorCall);
}
}
}
| 2,201 |
0 | Create_ds/PigPen/pigpen-pig/src/main/java | Create_ds/PigPen/pigpen-pig/src/main/java/pigpen/PigPenException.java | /*
*
* Copyright 2013-2015 Netflix, Inc.
*
* Licensed 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 pigpen;
import java.io.IOException;
/**
* An exception used to wrap Errors thrown from Clojure code as an IOException, which Pig can handle appropriately.
*
* @author mbossenbroek
*
*/
public class PigPenException extends IOException {
private static final long serialVersionUID = 1L;
/**
* Initialize a new PigPen exception.
*
* @param z The original exception
*/
public PigPenException(Throwable z) {
super(z);
setStackTrace(new StackTraceElement[0]);
}
}
| 2,202 |
0 | Create_ds/PigPen/pigpen-pig/src/main/java | Create_ds/PigPen/pigpen-pig/src/main/java/pigpen/PigPenFn.java | /*
*
* Copyright 2013-2015 Netflix, Inc.
*
* Licensed 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 pigpen;
import java.io.IOException;
import org.apache.pig.Accumulator;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.Tuple;
import clojure.lang.IFn;
import clojure.lang.RT;
import clojure.lang.Symbol;
import clojure.lang.Var;
/**
* Used to execute Clojure code from within a Pig UDF. Passes the tuple directly to pigpen.pig/eval-udf
*
* @author mbossenbroek
*
*/
public class PigPenFn extends EvalFunc<DataBag> implements Accumulator<DataBag> {
protected static final IFn EVAL_STRING, EXEC, EVAL, ACCUMULATE, GET_VALUE, CLEANUP;
static {
final Var require = RT.var("clojure.core", "require");
require.invoke(Symbol.intern("pigpen.pig.runtime"));
EVAL_STRING = RT.var("pigpen.pig.runtime", "eval-string");
EXEC = RT.var("pigpen.pig.runtime", "exec-transducer");
EVAL = RT.var("pigpen.pig.runtime", "eval-udf");
ACCUMULATE = RT.var("pigpen.pig.runtime", "udf-accumulate");
GET_VALUE = RT.var("pigpen.pig.runtime", "udf-get-value");
CLEANUP = RT.var("pigpen.pig.runtime", "udf-cleanup");
}
protected final Object func;
public PigPenFn(String init, String func) {
EVAL_STRING.invoke(init);
this.func = EXEC.invoke(EVAL_STRING.invoke(func));
}
@Override
public DataBag exec(Tuple input) throws IOException {
return (DataBag) EVAL.invoke(func, input);
}
private Object state = null;
@Override
public void accumulate(Tuple input) throws IOException {
state = ACCUMULATE.invoke(func, state, input);
}
@Override
public DataBag getValue() {
return (DataBag) GET_VALUE.invoke(state);
}
@Override
public void cleanup() {
state = CLEANUP.invoke(state);
}
}
| 2,203 |
0 | Create_ds/PigPen/pigpen-pig/src/main/java | Create_ds/PigPen/pigpen-pig/src/main/java/pigpen/PigPenPartitioner.java | /*
*
* Copyright 2014-2015 Netflix, Inc.
*
* Licensed 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 pigpen;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.pig.impl.io.PigNullableWritable;
import org.apache.pig.impl.util.UDFContext;
import clojure.lang.IFn;
import clojure.lang.RT;
import clojure.lang.Symbol;
import clojure.lang.Var;
/**
* The base class for partitioners in PigPen.
*
* @author mbossenbroek
*
*/
public abstract class PigPenPartitioner extends Partitioner<PigNullableWritable, Writable> {
private static final IFn EVAL_STRING, GET_PARTITION;
static {
final Var require = RT.var("clojure.core", "require");
require.invoke(Symbol.intern("pigpen.pig.runtime"));
EVAL_STRING = RT.var("pigpen.pig.runtime", "eval-string");
GET_PARTITION = RT.var("pigpen.pig.runtime", "get-partition");
}
private final String type;
private final Object func;
public PigPenPartitioner() {
final Configuration jobConf = UDFContext.getUDFContext().getJobConf();
type = jobConf.get(getClass().getSimpleName() + "_type");
final String init = jobConf.get(getClass().getSimpleName() + "_init");
final String funcString = jobConf.get(getClass().getSimpleName() + "_func");
EVAL_STRING.invoke(init);
this.func = EVAL_STRING.invoke(funcString);
}
@Override
public int getPartition(final PigNullableWritable key, final Writable value, final int numPartitions) {
return (Integer) GET_PARTITION.invoke(type, func, key.getValueAsPigType(), numPartitions);
}
// Hadoop doesn't allow for configuration of partitioners, so we make a lot of them
public static class PigPenPartitioner0 extends PigPenPartitioner {}
public static class PigPenPartitioner1 extends PigPenPartitioner {}
public static class PigPenPartitioner2 extends PigPenPartitioner {}
public static class PigPenPartitioner3 extends PigPenPartitioner {}
public static class PigPenPartitioner4 extends PigPenPartitioner {}
public static class PigPenPartitioner5 extends PigPenPartitioner {}
public static class PigPenPartitioner6 extends PigPenPartitioner {}
public static class PigPenPartitioner7 extends PigPenPartitioner {}
public static class PigPenPartitioner8 extends PigPenPartitioner {}
public static class PigPenPartitioner9 extends PigPenPartitioner {}
public static class PigPenPartitioner10 extends PigPenPartitioner {}
public static class PigPenPartitioner11 extends PigPenPartitioner {}
public static class PigPenPartitioner12 extends PigPenPartitioner {}
public static class PigPenPartitioner13 extends PigPenPartitioner {}
public static class PigPenPartitioner14 extends PigPenPartitioner {}
public static class PigPenPartitioner15 extends PigPenPartitioner {}
public static class PigPenPartitioner16 extends PigPenPartitioner {}
public static class PigPenPartitioner17 extends PigPenPartitioner {}
public static class PigPenPartitioner18 extends PigPenPartitioner {}
public static class PigPenPartitioner19 extends PigPenPartitioner {}
public static class PigPenPartitioner20 extends PigPenPartitioner {}
public static class PigPenPartitioner21 extends PigPenPartitioner {}
public static class PigPenPartitioner22 extends PigPenPartitioner {}
public static class PigPenPartitioner23 extends PigPenPartitioner {}
public static class PigPenPartitioner24 extends PigPenPartitioner {}
public static class PigPenPartitioner25 extends PigPenPartitioner {}
public static class PigPenPartitioner26 extends PigPenPartitioner {}
public static class PigPenPartitioner27 extends PigPenPartitioner {}
public static class PigPenPartitioner28 extends PigPenPartitioner {}
public static class PigPenPartitioner29 extends PigPenPartitioner {}
public static class PigPenPartitioner30 extends PigPenPartitioner {}
public static class PigPenPartitioner31 extends PigPenPartitioner {}
}
| 2,204 |
0 | Create_ds/PigPen/pigpen-pig/src/main/java | Create_ds/PigPen/pigpen-pig/src/main/java/pigpen/PigPenFnAlgebraic.java | /*
*
* Copyright 2013-2015 Netflix, Inc.
*
* Licensed 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 pigpen;
import java.io.IOException;
import org.apache.pig.Algebraic;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.DataByteArray;
import org.apache.pig.data.Tuple;
import clojure.lang.IFn;
import clojure.lang.Keyword;
import clojure.lang.RT;
import clojure.lang.Symbol;
import clojure.lang.Var;
/**
* Used to execute Clojure code from within a Pig UDF. This implements the Algebraic interface.
*
* @author mbossenbroek
*
*/
public class PigPenFnAlgebraic extends EvalFunc<DataByteArray> implements Algebraic {
private static final IFn EVAL_STRING, ALGEBRAIC;
private static final Keyword EXEC = RT.keyword(null, "exec");
private static final Keyword INITIAL = RT.keyword(null, "initial");
private static final Keyword INTERMED = RT.keyword(null, "intermed");
private static final Keyword FINAL = RT.keyword(null, "final");
static {
final Var require = RT.var("clojure.core", "require");
require.invoke(Symbol.intern("pigpen.pig.runtime"));
EVAL_STRING = RT.var("pigpen.pig.runtime", "eval-string");
ALGEBRAIC = RT.var("pigpen.pig.runtime", "udf-algebraic");
}
private final String initString, funcString;
private final Object func;
public PigPenFnAlgebraic(String init, String func) {
this.initString = init;
this.funcString = func;
EVAL_STRING.invoke(init);
this.func = EVAL_STRING.invoke(func);
}
@Override
public DataByteArray exec(final Tuple input) throws IOException {
return (DataByteArray) ALGEBRAIC.invoke(func, EXEC, input);
}
@Override
public String getInitial() {
return Initial.class.getName() + "('" + initString + "','" + funcString + "')";
}
@Override
public String getIntermed() {
return Intermed.class.getName() + "('" + initString + "','" + funcString + "')";
}
@Override
public String getFinal() {
return Final.class.getName() + "('" + initString + "','" + funcString + "')";
}
/**
* The Initial phase.
*/
public static class Initial extends EvalFunc<Tuple> {
private final Object func;
public Initial(String init, String func) {
// there are no words to describe how I feel about this crap
if (!init.equals("null")) {
EVAL_STRING.invoke(init);
this.func = EVAL_STRING.invoke(func);
} else {
this.func = null;
}
}
@Override
public Tuple exec(final Tuple input) throws IOException {
return (Tuple) ALGEBRAIC.invoke(func, INITIAL, input);
}
}
/**
* The Intermed phase.
*/
public static class Intermed extends EvalFunc<Tuple> {
private final Object func;
public Intermed(String init, String func) {
if (!init.equals("null")) {
EVAL_STRING.invoke(init);
this.func = EVAL_STRING.invoke(func);
} else {
this.func = null;
}
}
@Override
public Tuple exec(final Tuple input) throws IOException {
return (Tuple) ALGEBRAIC.invoke(func, INTERMED, input);
}
}
/**
* The Final phase.
*/
public static class Final extends EvalFunc<DataByteArray> {
private final Object func;
public Final(String init, String func) {
if (!init.equals("null")) {
EVAL_STRING.invoke(init);
this.func = EVAL_STRING.invoke(func);
} else {
this.func = null;
}
}
@Override
public DataByteArray exec(final Tuple input) throws IOException {
return (DataByteArray) ALGEBRAIC.invoke(func, FINAL, input);
}
}
}
| 2,205 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/ParameterMalleabilityTest.java | package software.amazon.encryption.s3;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.BUCKET;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.appendTestSuffix;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.deleteObject;
public class ParameterMalleabilityTest {
private static SecretKey AES_KEY;
@BeforeAll
public static void setUp() throws NoSuchAlgorithmException {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
AES_KEY = keyGen.generateKey();
}
@Test
public void contentEncryptionDowngradeAttackFails() {
final String objectKey = appendTestSuffix("content-downgrade-attack-fails");
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
final String input = "ContentDowngradeAttackFails";
// Encrypt something using AES-GCM
v3Client.putObject(builder -> builder.bucket(BUCKET).key(objectKey), RequestBody.fromString(input));
// Using a default client, tamper with the metadata
// CBC mode uses no parameter value, so just remove the "cek-alg" key
S3Client defaultClient = S3Client.builder().build();
ResponseInputStream<GetObjectResponse> response = defaultClient.getObject(builder -> builder.bucket(BUCKET).key(objectKey));
final Map<String, String> objectMetadata = response.response().metadata();
final Map<String, String> tamperedMetadata = new HashMap<>(objectMetadata);
tamperedMetadata.remove("x-amz-cek-alg");
// Replace the object with the content encryption algorithm removed
defaultClient.putObject(builder -> builder.bucket(BUCKET).key(objectKey).metadata(tamperedMetadata),
RequestBody.fromInputStream(response, response.response().contentLength()));
// getObject fails
assertThrows(Exception.class, () -> v3Client.getObject(builder -> builder.bucket(BUCKET).key(objectKey)));
// Enabling unauthenticated modes also fail
S3Client v3ClientUnauthenticated = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.enableLegacyUnauthenticatedModes(true)
.enableLegacyWrappingAlgorithms(true)
.build();
assertThrows(Exception.class, () -> v3ClientUnauthenticated.getObject(builder -> builder.bucket(BUCKET).key(objectKey)));
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void keyWrapRemovalAttackFails() {
final String objectKey = appendTestSuffix("keywrap-removal-attack-fails");
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
final String input = "KeyWrapRemovalAttackFails";
// Encrypt something using AES-GCM
v3Client.putObject(builder -> builder.bucket(BUCKET).key(objectKey), RequestBody.fromString(input));
// Using a default client, tamper with the metadata
S3Client defaultClient = S3Client.builder().build();
ResponseInputStream<GetObjectResponse> response = defaultClient.getObject(builder -> builder.bucket(BUCKET).key(objectKey));
final Map<String, String> objectMetadata = response.response().metadata();
final Map<String, String> tamperedMetadata = new HashMap<>(objectMetadata);
tamperedMetadata.remove("x-amz-wrap-alg");
// Replace the object
defaultClient.putObject(builder -> builder.bucket(BUCKET).key(objectKey).metadata(tamperedMetadata),
RequestBody.fromInputStream(response, response.response().contentLength()));
// getObject fails
assertThrows(Exception.class, () -> v3Client.getObject(builder -> builder.bucket(BUCKET).key(objectKey)));
// Enabling unauthenticated modes also fail
S3Client v3ClientUnauthenticated = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.enableLegacyUnauthenticatedModes(true)
.enableLegacyWrappingAlgorithms(true)
.build();
assertThrows(Exception.class, () -> v3ClientUnauthenticated.getObject(builder -> builder.bucket(BUCKET).key(objectKey)));
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void keyWrapDowngradeAesWrapAttackFails() {
final String objectKey = appendTestSuffix("keywrap-downgrade-aeswrap-attack-fails");
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
final String input = "KeyWrapDowngradeAesWrapAttackFails";
// Encrypt something using AES-GCM
v3Client.putObject(builder -> builder.bucket(BUCKET).key(objectKey), RequestBody.fromString(input));
// Using a default client, tamper with the metadata
S3Client defaultClient = S3Client.builder().build();
ResponseInputStream<GetObjectResponse> response = defaultClient.getObject(builder -> builder.bucket(BUCKET).key(objectKey));
final Map<String, String> objectMetadata = response.response().metadata();
final Map<String, String> tamperedMetadata = new HashMap<>(objectMetadata);
// Replace wrap-alg with AESWrap
tamperedMetadata.put("x-amz-wrap-alg", "AESWrap");
// Replace the object
defaultClient.putObject(builder -> builder.bucket(BUCKET).key(objectKey).metadata(tamperedMetadata),
RequestBody.fromInputStream(response, response.response().contentLength()));
// getObject fails
assertThrows(Exception.class, () -> v3Client.getObject(builder -> builder.bucket(BUCKET).key(objectKey)));
// Enabling unauthenticated modes also fail
S3Client v3ClientUnauthenticated = S3EncryptionClient.builder()
.enableLegacyWrappingAlgorithms(true)
.enableLegacyUnauthenticatedModes(true)
.aesKey(AES_KEY)
.build();
assertThrows(Exception.class, () -> v3ClientUnauthenticated.getObject(builder -> builder.bucket(BUCKET).key(objectKey)));
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void keyWrapDowngradeAesAttackFails() {
final String objectKey = appendTestSuffix("keywrap-downgrade-aes-attack-fails");
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
final String input = "KeyWrapDowngradeAesAttackFails";
// Encrypt something using AES-GCM
v3Client.putObject(builder -> builder.bucket(BUCKET).key(objectKey), RequestBody.fromString(input));
// Using a default client, tamper with the metadata
S3Client defaultClient = S3Client.builder().build();
ResponseInputStream<GetObjectResponse> response = defaultClient.getObject(builder -> builder.bucket(BUCKET).key(objectKey));
final Map<String, String> objectMetadata = response.response().metadata();
final Map<String, String> tamperedMetadata = new HashMap<>(objectMetadata);
// Replace wrap-alg with AES
tamperedMetadata.put("x-amz-wrap-alg", "AES");
// Replace the object
defaultClient.putObject(builder -> builder.bucket(BUCKET).key(objectKey).metadata(tamperedMetadata),
RequestBody.fromInputStream(response, response.response().contentLength()));
// getObject fails
assertThrows(Exception.class, () -> v3Client.getObject(builder -> builder.bucket(BUCKET).key(objectKey)));
// Enabling unauthenticated modes also fail
S3Client v3ClientUnauthenticated = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.enableLegacyWrappingAlgorithms(true)
.enableLegacyUnauthenticatedModes(true)
.build();
assertThrows(Exception.class, () -> v3ClientUnauthenticated.getObject(builder -> builder.bucket(BUCKET).key(objectKey)));
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
}
| 2,206 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/S3EncryptionClientCRTTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3;
import com.amazonaws.services.s3.AmazonS3Encryption;
import com.amazonaws.services.s3.AmazonS3EncryptionClient;
import com.amazonaws.services.s3.model.CryptoConfiguration;
import com.amazonaws.services.s3.model.EncryptionMaterials;
import com.amazonaws.services.s3.model.EncryptionMaterialsProvider;
import com.amazonaws.services.s3.model.StaticEncryptionMaterialsProvider;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.CompletionException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.BUCKET;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.appendTestSuffix;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.deleteObject;
/**
* This class is an integration test for Unauthenticated Ranged Get for AES/CBC and AES/GCM modes
*/
public class S3EncryptionClientCRTTest {
private static SecretKey AES_KEY;
@BeforeAll
public static void setUp() throws NoSuchAlgorithmException {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
AES_KEY = keyGen.generateKey();
}
@Test
public void AsyncAesGcmV3toV3RangedGet() {
final String objectKey = appendTestSuffix("async-aes-gcm-v3-to-v3-ranged-get");
final String input = "0bcdefghijklmnopqrst0BCDEFGHIJKLMNOPQRST" +
"1bcdefghijklmnopqrst1BCDEFGHIJKLMNOPQRST" +
"2bcdefghijklmnopqrst2BCDEFGHIJKLMNOPQRST" +
"3bcdefghijklmnopqrst3BCDEFGHIJKLMNOPQRST" +
"4bcdefghijklmnopqrst4BCDEFGHIJKLMNOPQRST";
// Async Client
S3AsyncClient asyncClient = S3AsyncEncryptionClient.builder()
.aesKey(AES_KEY)
.enableLegacyUnauthenticatedModes(true)
.wrappedClient(S3AsyncClient.crtCreate())
.build();
asyncClient.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), AsyncRequestBody.fromString(input)).join();
// Valid Range
ResponseBytes<GetObjectResponse> objectResponse = asyncClient.getObject(builder -> builder
.bucket(BUCKET)
.range("bytes=10-20")
.key(objectKey), AsyncResponseTransformer.toBytes()).join();
String output = objectResponse.asUtf8String();
assertEquals("klmnopqrst0", output);
// Valid start index within input and end index out of range, returns object from start index to End of Stream
objectResponse = asyncClient.getObject(builder -> builder
.bucket(BUCKET)
.range("bytes=190-300")
.key(objectKey), AsyncResponseTransformer.toBytes()).join();
output = objectResponse.asUtf8String();
assertEquals("KLMNOPQRST", output);
// Invalid range start index range greater than ending index, returns entire object
objectResponse = asyncClient.getObject(builder -> builder
.bucket(BUCKET)
.range("bytes=100-50")
.key(objectKey), AsyncResponseTransformer.toBytes()).join();
output = objectResponse.asUtf8String();
assertEquals(input, output);
// Invalid range format, returns entire object
objectResponse = asyncClient.getObject(builder -> builder
.bucket(BUCKET)
.range("10-20")
.key(objectKey), AsyncResponseTransformer.toBytes()).join();
output = objectResponse.asUtf8String();
assertEquals(input, output);
// Invalid range starting index and ending index greater than object length but within Cipher Block size, returns empty object
objectResponse = asyncClient.getObject(builder -> builder
.bucket(BUCKET)
.range("bytes=216-217")
.key(objectKey), AsyncResponseTransformer.toBytes()).join();
output = objectResponse.asUtf8String();
assertEquals("", output);
// Cleanup
deleteObject(BUCKET, objectKey, asyncClient);
asyncClient.close();
}
@Test
public void AsyncFailsOnRangeWhenLegacyModeDisabled() {
final String objectKey = appendTestSuffix("fails-when-on-range-when-legacy-disabled");
final String input = "0bcdefghijklmnopqrst0BCDEFGHIJKLMNOPQRST" +
"1bcdefghijklmnopqrst1BCDEFGHIJKLMNOPQRST" +
"2bcdefghijklmnopqrst2BCDEFGHIJKLMNOPQRST" +
"3bcdefghijklmnopqrst3BCDEFGHIJKLMNOPQRST" +
"4bcdefghijklmnopqrst4BCDEFGHIJKLMNOPQRST";
// V3 Client
S3AsyncClient asyncClient = S3AsyncEncryptionClient.builder()
.wrappedClient(S3AsyncClient.crtCreate())
.aesKey(AES_KEY)
.build();
asyncClient.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), AsyncRequestBody.fromString(input)).join();
assertThrows(S3EncryptionClientException.class, () -> asyncClient.getObject(builder -> builder
.bucket(BUCKET)
.range("bytes=10-20")
.key(objectKey), AsyncResponseTransformer.toBytes()).join());
// Cleanup
deleteObject(BUCKET, objectKey, asyncClient);
asyncClient.close();
}
@Test
public void AsyncAesCbcV1toV3RangedGet() {
final String objectKey = appendTestSuffix("aes-cbc-v1-to-v3-ranged-get-async");
// V1 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
CryptoConfiguration v1CryptoConfig =
new CryptoConfiguration();
AmazonS3Encryption v1Client = AmazonS3EncryptionClient.encryptionBuilder()
.withCryptoConfiguration(v1CryptoConfig)
.withEncryptionMaterials(materialsProvider)
.build();
final String input = "0bcdefghijklmnopqrst0BCDEFGHIJKLMNOPQRST" +
"1bcdefghijklmnopqrst1BCDEFGHIJKLMNOPQRST" +
"2bcdefghijklmnopqrst2BCDEFGHIJKLMNOPQRST" +
"3bcdefghijklmnopqrst3BCDEFGHIJKLMNOPQRST" +
"4bcdefghijklmnopqrst4BCDEFGHIJKLMNOPQRST";
v1Client.putObject(BUCKET, objectKey, input);
// V3 Client
S3AsyncClient v3Client = S3AsyncEncryptionClient.builder()
.aesKey(AES_KEY)
.wrappedClient(S3AsyncClient.crtCreate())
.enableLegacyWrappingAlgorithms(true)
.enableLegacyUnauthenticatedModes(true)
.build();
// Valid Range
ResponseBytes<GetObjectResponse> objectResponse;
objectResponse = v3Client.getObject(builder -> builder
.bucket(BUCKET)
.range("bytes=10-20")
.key(objectKey), AsyncResponseTransformer.toBytes()).join();
String output;
output = objectResponse.asUtf8String();
assertEquals("klmnopqrst0", output);
// Valid start index within input and end index out of range, returns object from start index to End of Stream
objectResponse = v3Client.getObject(builder -> builder
.bucket(BUCKET)
.range("bytes=190-300")
.key(objectKey), AsyncResponseTransformer.toBytes()).join();
output = objectResponse.asUtf8String();
assertEquals("KLMNOPQRST", output);
// Invalid range start index range greater than ending index, returns entire object
objectResponse = v3Client.getObject(builder -> builder
.bucket(BUCKET)
.range("bytes=100-50")
.key(objectKey), AsyncResponseTransformer.toBytes()).join();
output = objectResponse.asUtf8String();
assertEquals(input, output);
// Invalid range format, returns entire object
objectResponse = v3Client.getObject(builder -> builder
.bucket(BUCKET)
.range("10-20")
.key(objectKey), AsyncResponseTransformer.toBytes()).join();
output = objectResponse.asUtf8String();
assertEquals(input, output);
// Invalid range starting index and ending index greater than object length but within Cipher Block size, returns empty object
objectResponse = v3Client.getObject(builder -> builder
.bucket(BUCKET)
.range("bytes=216-217")
.key(objectKey), AsyncResponseTransformer.toBytes()).join();
output = objectResponse.asUtf8String();
assertEquals("", output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void failsOnRangeWhenLegacyModeDisabled() {
final String objectKey = appendTestSuffix("fails-when-on-range-when-legacy-disabled");
final String input = "0bcdefghijklmnopqrst0BCDEFGHIJKLMNOPQRST" +
"1bcdefghijklmnopqrst1BCDEFGHIJKLMNOPQRST" +
"2bcdefghijklmnopqrst2BCDEFGHIJKLMNOPQRST" +
"3bcdefghijklmnopqrst3BCDEFGHIJKLMNOPQRST" +
"4bcdefghijklmnopqrst4BCDEFGHIJKLMNOPQRST";
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.wrappedAsyncClient(S3AsyncClient.crtCreate())
.aesKey(AES_KEY)
.build();
v3Client.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), RequestBody.fromString(input));
// Asserts
assertThrows(S3EncryptionClientException.class, () -> v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.range("bytes=10-20")));
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void AesGcmV3toV3RangedGet() {
final String objectKey = appendTestSuffix("aes-gcm-v3-to-v3-ranged-get");
final String input = "0bcdefghijklmnopqrst0BCDEFGHIJKLMNOPQRST" +
"1bcdefghijklmnopqrst1BCDEFGHIJKLMNOPQRST" +
"2bcdefghijklmnopqrst2BCDEFGHIJKLMNOPQRST" +
"3bcdefghijklmnopqrst3BCDEFGHIJKLMNOPQRST" +
"4bcdefghijklmnopqrst4BCDEFGHIJKLMNOPQRST";
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.wrappedAsyncClient(S3AsyncClient.crtCreate())
.aesKey(AES_KEY)
.enableLegacyUnauthenticatedModes(true)
.build();
v3Client.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), RequestBody.fromString(input));
// Valid Range
ResponseBytes<GetObjectResponse> objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("bytes=10-20")
.key(objectKey));
String output = objectResponse.asUtf8String();
assertEquals("klmnopqrst0", output);
// Valid start index within input and end index out of range, returns object from start index to End of Stream
objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("bytes=190-300")
.key(objectKey));
output = objectResponse.asUtf8String();
assertEquals("KLMNOPQRST", output);
// Invalid range start index range greater than ending index, returns entire object
objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("bytes=100-50")
.key(objectKey));
output = objectResponse.asUtf8String();
assertEquals(input, output);
// Invalid range format, returns entire object
objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("10-20")
.key(objectKey));
output = objectResponse.asUtf8String();
assertEquals(input, output);
// Invalid range starting index and ending index greater than object length but within Cipher Block size, returns empty object
objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("bytes=216-217")
.key(objectKey));
output = objectResponse.asUtf8String();
assertEquals("", output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void AesGcmV3toV3FailsRangeExceededObjectLength() {
final String objectKey = appendTestSuffix("aes-gcm-v3-to-v3-ranged-get-out-of-range");
final String input = "0bcdefghijklmnopqrst0BCDEFGHIJKLMNOPQRST" +
"1bcdefghijklmnopqrst1BCDEFGHIJKLMNOPQRST" +
"2bcdefghijklmnopqrst2BCDEFGHIJKLMNOPQRST" +
"3bcdefghijklmnopqrst3BCDEFGHIJKLMNOPQRST" +
"4bcdefghijklmnopqrst4BCDEFGHIJKLMNOPQRST";
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.wrappedAsyncClient(S3AsyncClient.crtCreate())
.aesKey(AES_KEY)
.enableLegacyUnauthenticatedModes(true)
.build();
v3Client.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), RequestBody.fromString(input));
// Invalid range exceed object length, Throws S3EncryptionClientException wrapped with S3Exception
assertThrows(S3EncryptionClientException.class, () -> v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("bytes=300-400")
.key(objectKey)));
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void AsyncAesGcmV3toV3FailsRangeExceededObjectLength() {
final String objectKey = appendTestSuffix("aes-gcm-v3-to-v3-ranged-get-out-of-range");
final String input = "0bcdefghijklmnopqrst0BCDEFGHIJKLMNOPQRST" +
"1bcdefghijklmnopqrst1BCDEFGHIJKLMNOPQRST" +
"2bcdefghijklmnopqrst2BCDEFGHIJKLMNOPQRST" +
"3bcdefghijklmnopqrst3BCDEFGHIJKLMNOPQRST" +
"4bcdefghijklmnopqrst4BCDEFGHIJKLMNOPQRST";
// Async Client
S3AsyncClient asyncClient = S3AsyncEncryptionClient.builder()
.wrappedClient(S3AsyncClient.crtCreate())
.aesKey(AES_KEY)
.enableLegacyUnauthenticatedModes(true)
.build();
asyncClient.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), AsyncRequestBody.fromString(input)).join();
try {
// Invalid range exceed object length, Throws S3Exception nested inside CompletionException
asyncClient.getObject(builder -> builder
.bucket(BUCKET)
.range("bytes=300-400")
.key(objectKey), AsyncResponseTransformer.toBytes()).join();
} catch (CompletionException e) {
assertEquals(S3Exception.class, e.getCause().getClass());
}
// Cleanup
deleteObject(BUCKET, objectKey, asyncClient);
asyncClient.close();
}
@Test
public void AesCbcV1toV3RangedGet() {
final String objectKey = appendTestSuffix("aes-cbc-v1-to-v3-ranged-get");
// V1 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
CryptoConfiguration v1CryptoConfig =
new CryptoConfiguration();
AmazonS3Encryption v1Client = AmazonS3EncryptionClient.encryptionBuilder()
.withCryptoConfiguration(v1CryptoConfig)
.withEncryptionMaterials(materialsProvider)
.build();
// This string is 200 characters/bytes long
// Due to padding, its ciphertext will be 208 bytes
final String input = "0bcdefghijklmnopqrst0BCDEFGHIJKLMNOPQRST" +
"1bcdefghijklmnopqrst1BCDEFGHIJKLMNOPQRST" +
"2bcdefghijklmnopqrst2BCDEFGHIJKLMNOPQRST" +
"3bcdefghijklmnopqrst3BCDEFGHIJKLMNOPQRST" +
"4bcdefghijklmnopqrst4BCDEFGHIJKLMNOPQRST";
v1Client.putObject(BUCKET, objectKey, input);
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.wrappedAsyncClient(S3AsyncClient.crtCreate())
.aesKey(AES_KEY)
.enableLegacyWrappingAlgorithms(true)
.enableLegacyUnauthenticatedModes(true)
.build();
// Valid Range
ResponseBytes<GetObjectResponse> objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("bytes=10-20")
.key(objectKey));
String output = objectResponse.asUtf8String();
assertEquals("klmnopqrst0", output);
// Valid start index within input and end index out of range, returns object from start index to End of Stream
objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("bytes=190-300")
.key(objectKey));
output = objectResponse.asUtf8String();
assertEquals("KLMNOPQRST", output);
// Invalid range start index range greater than ending index, returns entire object
objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("bytes=100-50")
.key(objectKey));
output = objectResponse.asUtf8String();
assertEquals(input, output);
// Invalid range format, returns entire object
objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("10-20")
.key(objectKey));
output = objectResponse.asUtf8String();
assertEquals(input, output);
// Invalid range starting index and ending index greater than object length
// but within Cipher Block size, returns empty object
objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("bytes=216-217")
.key(objectKey));
output = objectResponse.asUtf8String();
assertEquals("", output);
// Invalid range starting index and ending index greater than object length
// but within Cipher Block size, returns empty object
objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("bytes=216-218")
.key(objectKey));
output = objectResponse.asUtf8String();
assertEquals("", output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void AesCbcV1toV3FailsRangeExceededObjectLength() {
final String objectKey = appendTestSuffix("aes-cbc-v1-to-v3-ranged-get-out-of-range");
// V1 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
CryptoConfiguration v1CryptoConfig =
new CryptoConfiguration();
AmazonS3Encryption v1Client = AmazonS3EncryptionClient.encryptionBuilder()
.withCryptoConfiguration(v1CryptoConfig)
.withEncryptionMaterials(materialsProvider)
.build();
final String input = "0bcdefghijklmnopqrst0BCDEFGHIJKLMNOPQRST" +
"1bcdefghijklmnopqrst1BCDEFGHIJKLMNOPQRST" +
"2bcdefghijklmnopqrst2BCDEFGHIJKLMNOPQRST" +
"3bcdefghijklmnopqrst3BCDEFGHIJKLMNOPQRST" +
"4bcdefghijklmnopqrst4BCDEFGHIJKLMNOPQRST";
v1Client.putObject(BUCKET, objectKey, input);
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.enableLegacyWrappingAlgorithms(true)
.enableLegacyUnauthenticatedModes(true)
.wrappedAsyncClient(S3AsyncClient.crtCreate())
.build();
// Invalid range exceed object length, Throws S3EncryptionClientException wrapped with S3Exception
assertThrows(S3EncryptionClientException.class, () -> v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("bytes=300-400")
.key(objectKey)));
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
}
| 2,207 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/S3EncryptionClientCompatibilityTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.kms.AWSKMS;
import com.amazonaws.services.kms.AWSKMSClientBuilder;
import com.amazonaws.services.s3.AmazonS3Encryption;
import com.amazonaws.services.s3.AmazonS3EncryptionClient;
import com.amazonaws.services.s3.AmazonS3EncryptionClientV2;
import com.amazonaws.services.s3.AmazonS3EncryptionV2;
import com.amazonaws.services.s3.model.CryptoConfiguration;
import com.amazonaws.services.s3.model.CryptoConfigurationV2;
import com.amazonaws.services.s3.model.CryptoMode;
import com.amazonaws.services.s3.model.CryptoStorageMode;
import com.amazonaws.services.s3.model.EncryptedPutObjectRequest;
import com.amazonaws.services.s3.model.EncryptionMaterials;
import com.amazonaws.services.s3.model.EncryptionMaterialsProvider;
import com.amazonaws.services.s3.model.KMSEncryptionMaterials;
import com.amazonaws.services.s3.model.KMSEncryptionMaterialsProvider;
import com.amazonaws.services.s3.model.StaticEncryptionMaterialsProvider;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static software.amazon.encryption.s3.S3EncryptionClient.withAdditionalConfiguration;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.appendTestSuffix;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.deleteObject;
/**
* This class is an integration test for verifying compatibility of ciphertexts
* between V1, V2, and V3 clients under various conditions.
*/
public class S3EncryptionClientCompatibilityTest {
private static final String BUCKET = System.getenv("AWS_S3EC_TEST_BUCKET");
private static final String KMS_KEY_ID = System.getenv("AWS_S3EC_TEST_KMS_KEY_ID");
private static final Region KMS_REGION = Region.getRegion(Regions.fromName(System.getenv("AWS_REGION")));
private static SecretKey AES_KEY;
private static KeyPair RSA_KEY_PAIR;
@BeforeAll
public static void setUp() throws NoSuchAlgorithmException {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
AES_KEY = keyGen.generateKey();
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(2048);
RSA_KEY_PAIR = keyPairGen.generateKeyPair();
}
@Test
public void AesCbcV1toV3() {
final String objectKey = appendTestSuffix("aes-cbc-v1-to-v3");
// V1 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
CryptoConfiguration v1CryptoConfig =
new CryptoConfiguration(CryptoMode.EncryptionOnly);
AmazonS3Encryption v1Client = AmazonS3EncryptionClient.encryptionBuilder()
.withCryptoConfiguration(v1CryptoConfig)
.withEncryptionMaterials(materialsProvider)
.build();
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.enableLegacyWrappingAlgorithms(true)
.enableLegacyUnauthenticatedModes(true)
.build();
// Asserts
final String input = "AesCbcV1toV3";
v1Client.putObject(BUCKET, objectKey, input);
ResponseBytes<GetObjectResponse> objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey));
String output = objectResponse.asUtf8String();
assertEquals(input, output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void AesWrapV1toV3() {
final String objectKey = appendTestSuffix("aes-wrap-v1-to-v3");
// V1 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
CryptoConfiguration v1CryptoConfig =
new CryptoConfiguration(CryptoMode.AuthenticatedEncryption);
AmazonS3Encryption v1Client = AmazonS3EncryptionClient.encryptionBuilder()
.withCryptoConfiguration(v1CryptoConfig)
.withEncryptionMaterials(materialsProvider)
.build();
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.enableLegacyWrappingAlgorithms(true)
.build();
// Asserts
final String input = "AesGcmV1toV3";
v1Client.putObject(BUCKET, objectKey, input);
ResponseBytes<GetObjectResponse> objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey));
String output = objectResponse.asUtf8String();
assertEquals(input, output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void AesGcmV2toV3() {
final String objectKey = appendTestSuffix("aes-gcm-v2-to-v3");
// V2 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
AmazonS3EncryptionV2 v2Client = AmazonS3EncryptionClientV2.encryptionBuilder()
.withEncryptionMaterialsProvider(materialsProvider)
.build();
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
// Asserts
final String input = "AesGcmV2toV3";
v2Client.putObject(BUCKET, objectKey, input);
ResponseBytes<GetObjectResponse> objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey));
String output = objectResponse.asUtf8String();
assertEquals(input, output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void AesGcmV2toV3WithInstructionFile() {
final String objectKey = appendTestSuffix("aes-gcm-v2-to-v3-with-instruction-file");
// V2 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
CryptoConfigurationV2 cryptoConfig =
new CryptoConfigurationV2(CryptoMode.StrictAuthenticatedEncryption)
.withStorageMode(CryptoStorageMode.InstructionFile);
AmazonS3EncryptionV2 v2Client = AmazonS3EncryptionClientV2.encryptionBuilder()
.withCryptoConfiguration(cryptoConfig)
.withEncryptionMaterialsProvider(materialsProvider)
.build();
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
// Asserts
final String input = "AesGcmV2toV3";
v2Client.putObject(BUCKET, objectKey, input);
ResponseBytes<GetObjectResponse> objectResponse = v3Client.getObjectAsBytes(
GetObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey).build());
String output = objectResponse.asUtf8String();
assertEquals(input, output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void AesGcmV3toV1() {
final String objectKey = appendTestSuffix("aes-gcm-v3-to-v1");
// V1 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
CryptoConfiguration v1CryptoConfig =
new CryptoConfiguration(CryptoMode.AuthenticatedEncryption);
AmazonS3Encryption v1Client = AmazonS3EncryptionClient.encryptionBuilder()
.withCryptoConfiguration(v1CryptoConfig)
.withEncryptionMaterials(materialsProvider)
.build();
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
// Asserts
final String input = "AesGcmV3toV1";
v3Client.putObject(builder -> builder
.bucket(BUCKET)
.key(objectKey), RequestBody.fromString(input));
String output = v1Client.getObjectAsString(BUCKET, objectKey);
assertEquals(input, output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void AesGcmV3toV2() {
final String objectKey = appendTestSuffix("aes-gcm-v3-to-v2");
// V2 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
AmazonS3EncryptionV2 v2Client = AmazonS3EncryptionClientV2.encryptionBuilder()
.withEncryptionMaterialsProvider(materialsProvider)
.build();
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
// Asserts
final String input = "AesGcmV3toV2";
v3Client.putObject(builder -> builder
.bucket(BUCKET)
.key(objectKey), RequestBody.fromString(input));
String output = v2Client.getObjectAsString(BUCKET, objectKey);
assertEquals(input, output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void AesGcmV3toV3() {
final String objectKey = appendTestSuffix("aes-gcm-v3-to-v3");
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
// Asserts
final String input = "AesGcmV3toV3";
v3Client.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), RequestBody.fromString(input));
ResponseBytes<GetObjectResponse> objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey));
String output = objectResponse.asUtf8String();
assertEquals(input, output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void RsaV1toV3() {
final String objectKey = appendTestSuffix("v1-rsa-to-v3");
EncryptionMaterialsProvider materialsProvider = new StaticEncryptionMaterialsProvider(new EncryptionMaterials(RSA_KEY_PAIR));
AmazonS3Encryption v1Client = AmazonS3EncryptionClient.encryptionBuilder()
.withEncryptionMaterials(materialsProvider)
.build();
S3Client v3Client = S3EncryptionClient.builder()
.rsaKeyPair(RSA_KEY_PAIR)
.enableLegacyWrappingAlgorithms(true)
.enableLegacyUnauthenticatedModes(true)
.build();
final String input = "This is some content to encrypt using the v1 client";
v1Client.putObject(BUCKET, objectKey, input);
ResponseBytes<GetObjectResponse> objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.build());
String output = objectResponse.asUtf8String();
assertEquals(input, output);
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void RsaV1toV3AesFails() {
final String objectKey = appendTestSuffix("v1-rsa-to-v3-aes-fails");
EncryptionMaterialsProvider materialsProvider = new StaticEncryptionMaterialsProvider(new EncryptionMaterials(RSA_KEY_PAIR));
AmazonS3Encryption v1Client = AmazonS3EncryptionClient.encryptionBuilder()
.withEncryptionMaterials(materialsProvider)
.build();
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.enableLegacyWrappingAlgorithms(true)
.enableLegacyUnauthenticatedModes(true)
.build();
final String input = "This is some content to encrypt using the v1 client";
v1Client.putObject(BUCKET, objectKey, input);
assertThrows(S3EncryptionClientException.class, () -> v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.build()));
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void RsaEcbV1toV3() {
final String objectKey = appendTestSuffix("rsa-ecb-v1-to-v3");
// V1 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(RSA_KEY_PAIR));
CryptoConfiguration v1CryptoConfig =
new CryptoConfiguration(CryptoMode.AuthenticatedEncryption);
AmazonS3Encryption v1Client = AmazonS3EncryptionClient.encryptionBuilder()
.withCryptoConfiguration(v1CryptoConfig)
.withEncryptionMaterials(materialsProvider)
.build();
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.rsaKeyPair(RSA_KEY_PAIR)
.enableLegacyWrappingAlgorithms(true)
.build();
// Asserts
final String input = "RsaEcbV1toV3";
v1Client.putObject(BUCKET, objectKey, input);
ResponseBytes<GetObjectResponse> objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey));
String output = objectResponse.asUtf8String();
assertEquals(input, output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void RsaOaepV2toV3() {
final String objectKey = appendTestSuffix("rsa-oaep-v2-to-v3");
// V2 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(RSA_KEY_PAIR));
CryptoConfigurationV2 cryptoConfig =
new CryptoConfigurationV2(CryptoMode.StrictAuthenticatedEncryption);
AmazonS3EncryptionV2 v2Client = AmazonS3EncryptionClientV2.encryptionBuilder()
.withCryptoConfiguration(cryptoConfig)
.withEncryptionMaterialsProvider(materialsProvider)
.build();
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.rsaKeyPair(RSA_KEY_PAIR)
.build();
// Asserts
final String input = "RsaOaepV2toV3";
v2Client.putObject(BUCKET, objectKey, input);
ResponseBytes<GetObjectResponse> objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey));
String output = objectResponse.asUtf8String();
assertEquals(input, output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void RsaOaepV3toV1() {
final String objectKey = appendTestSuffix("rsa-oaep-v3-to-v1");
// V1 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(RSA_KEY_PAIR));
CryptoConfiguration v1CryptoConfig =
new CryptoConfiguration(CryptoMode.AuthenticatedEncryption);
AmazonS3Encryption v1Client = AmazonS3EncryptionClient.encryptionBuilder()
.withCryptoConfiguration(v1CryptoConfig)
.withEncryptionMaterials(materialsProvider)
.build();
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.rsaKeyPair(RSA_KEY_PAIR)
.build();
// Asserts
final String input = "RsaOaepV3toV1";
v3Client.putObject(builder -> builder
.bucket(BUCKET)
.key(objectKey), RequestBody.fromString(input));
String output = v1Client.getObjectAsString(BUCKET, objectKey);
assertEquals(input, output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void RsaOaepV3toV2() {
final String objectKey = appendTestSuffix("rsa-oaep-v3-to-v2");
// V2 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(RSA_KEY_PAIR));
AmazonS3EncryptionV2 v2Client = AmazonS3EncryptionClientV2.encryptionBuilder()
.withEncryptionMaterialsProvider(materialsProvider)
.build();
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.rsaKeyPair(RSA_KEY_PAIR)
.build();
// Asserts
final String input = "RsaOaepV3toV2";
v3Client.putObject(builder -> builder
.bucket(BUCKET)
.key(objectKey), RequestBody.fromString(input));
String output = v2Client.getObjectAsString(BUCKET, objectKey);
assertEquals(input, output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void RsaOaepV3toV3() {
final String objectKey = appendTestSuffix("rsa-oaep-v3-to-v3");
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.rsaKeyPair(RSA_KEY_PAIR)
.build();
// Asserts
final String input = "RsaOaepV3toV3";
v3Client.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), RequestBody.fromString(input));
ResponseBytes<GetObjectResponse> objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey));
String output = objectResponse.asUtf8String();
assertEquals(input, output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void KmsCBCV1ToV3() {
String objectKey = appendTestSuffix("v1-kms-cbc-to-v3");
AWSKMS kmsClient = AWSKMSClientBuilder.standard()
.withRegion(KMS_REGION.toString())
.build();
EncryptionMaterialsProvider materialsProvider = new KMSEncryptionMaterialsProvider(KMS_KEY_ID);
// v1 Client in default mode
AmazonS3Encryption v1Client = AmazonS3EncryptionClient.encryptionBuilder()
.withEncryptionMaterials(materialsProvider)
.withKmsClient(kmsClient)
.build();
S3Client v3Client = S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.enableLegacyUnauthenticatedModes(true)
.enableLegacyWrappingAlgorithms(true)
.build();
String input = "This is some content to encrypt using v1 client";
v1Client.putObject(BUCKET, objectKey, input);
ResponseBytes<GetObjectResponse> objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.build());
String output = objectResponse.asUtf8String();
assertEquals(input, output);
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void KmsV1toV3() {
final String objectKey = appendTestSuffix("kms-v1-to-v3");
// V1 Client
EncryptionMaterialsProvider materialsProvider = new KMSEncryptionMaterialsProvider(KMS_KEY_ID);
CryptoConfiguration v1Config =
new CryptoConfiguration(CryptoMode.AuthenticatedEncryption)
.withAwsKmsRegion(KMS_REGION);
AmazonS3Encryption v1Client = AmazonS3EncryptionClient.encryptionBuilder()
.withCryptoConfiguration(v1Config)
.withEncryptionMaterials(materialsProvider)
.build();
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.enableLegacyWrappingAlgorithms(true)
.build();
// Asserts
final String input = "KmsV1toV3";
v1Client.putObject(BUCKET, objectKey, input);
ResponseBytes<GetObjectResponse> objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey));
String output = objectResponse.asUtf8String();
assertEquals(input, output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void KmsContextV2toV3() {
final String objectKey = appendTestSuffix("kms-context-v2-to-v3");
// V2 Client
EncryptionMaterialsProvider materialsProvider = new KMSEncryptionMaterialsProvider(KMS_KEY_ID);
AmazonS3EncryptionV2 v2Client = AmazonS3EncryptionClientV2.encryptionBuilder()
.withEncryptionMaterialsProvider(materialsProvider)
.build();
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.build();
// Asserts
final String input = "KmsContextV2toV3";
Map<String, String> encryptionContext = new HashMap<>();
encryptionContext.put("user-metadata-key", "user-metadata-value");
EncryptedPutObjectRequest putObjectRequest = new EncryptedPutObjectRequest(
BUCKET,
objectKey,
new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)),
null
).withMaterialsDescription(encryptionContext);
v2Client.putObject(putObjectRequest);
ResponseBytes<GetObjectResponse> objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.overrideConfiguration(withAdditionalConfiguration(encryptionContext)));
String output = objectResponse.asUtf8String();
assertEquals(input, output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void KmsContextV3toV1() {
final String objectKey = appendTestSuffix("kms-context-v3-to-v1");
// V1 Client
KMSEncryptionMaterials kmsMaterials = new KMSEncryptionMaterials(KMS_KEY_ID);
kmsMaterials.addDescription("user-metadata-key", "user-metadata-value-v3-to-v1");
EncryptionMaterialsProvider materialsProvider = new KMSEncryptionMaterialsProvider(kmsMaterials);
CryptoConfiguration v1Config =
new CryptoConfiguration(CryptoMode.AuthenticatedEncryption)
.withAwsKmsRegion(KMS_REGION);
AmazonS3Encryption v1Client = AmazonS3EncryptionClient.encryptionBuilder()
.withCryptoConfiguration(v1Config)
.withEncryptionMaterials(materialsProvider)
.build();
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.build();
// Asserts
final String input = "KmsContextV3toV1";
Map<String, String> encryptionContext = new HashMap<>();
encryptionContext.put("user-metadata-key", "user-metadata-value-v3-to-v1");
v3Client.putObject(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.overrideConfiguration(withAdditionalConfiguration(encryptionContext)), RequestBody.fromString(input));
String output = v1Client.getObjectAsString(BUCKET, objectKey);
assertEquals(input, output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void KmsContextV3toV2() throws IOException {
final String objectKey = appendTestSuffix("kms-context-v3-to-v2");
// V2 Client
KMSEncryptionMaterials kmsMaterials = new KMSEncryptionMaterials(KMS_KEY_ID);
kmsMaterials.addDescription("user-metadata-key", "user-metadata-value-v3-to-v2");
EncryptionMaterialsProvider materialsProvider = new KMSEncryptionMaterialsProvider(kmsMaterials);
AmazonS3EncryptionV2 v2Client = AmazonS3EncryptionClientV2.encryptionBuilder()
.withEncryptionMaterialsProvider(materialsProvider)
.build();
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.build();
// Asserts
final String input = "KmsContextV3toV2";
Map<String, String> encryptionContext = new HashMap<>();
encryptionContext.put("user-metadata-key", "user-metadata-value-v3-to-v2");
v3Client.putObject(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.overrideConfiguration(withAdditionalConfiguration(encryptionContext)),
RequestBody.fromString(input));
String output = v2Client.getObjectAsString(BUCKET, objectKey);
assertEquals(input, output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void KmsContextV3toV3() {
final String objectKey = appendTestSuffix("kms-context-v3-to-v3");
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.build();
// Asserts
final String input = "KmsContextV3toV3";
Map<String, String> encryptionContext = new HashMap<>();
encryptionContext.put("user-metadata-key", "user-metadata-value-v3-to-v3");
v3Client.putObject(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.overrideConfiguration(withAdditionalConfiguration(encryptionContext)),
RequestBody.fromString(input));
ResponseBytes<GetObjectResponse> objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.overrideConfiguration(withAdditionalConfiguration(encryptionContext)));
String output = objectResponse.asUtf8String();
assertEquals(input, output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void KmsContextV3toV3MismatchFails() {
final String objectKey = appendTestSuffix("kms-context-v3-to-v3");
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.build();
// Asserts
final String input = "KmsContextV3toV3";
Map<String, String> encryptionContext = new HashMap<>();
encryptionContext.put("user-metadata-key", "user-metadata-value-v3-to-v3");
v3Client.putObject(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.overrideConfiguration(withAdditionalConfiguration(encryptionContext)),
RequestBody.fromString(input));
// Use the wrong EC
Map<String, String> otherEncryptionContext = new HashMap<>();
otherEncryptionContext.put("user-metadata-key", "!user-metadata-value-v3-to-v3");
assertThrows(S3EncryptionClientException.class, () -> v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.overrideConfiguration(withAdditionalConfiguration(otherEncryptionContext))));
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void AesCbcV1toV3FailsWhenLegacyModeDisabled() {
final String objectKey = appendTestSuffix("aes-cbc-v1-to-v3");
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
CryptoConfiguration v1CryptoConfig =
new CryptoConfiguration(CryptoMode.EncryptionOnly);
AmazonS3Encryption v1Client = AmazonS3EncryptionClient.encryptionBuilder()
.withCryptoConfiguration(v1CryptoConfig)
.withEncryptionMaterials(materialsProvider)
.build();
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.enableLegacyWrappingAlgorithms(false)
.enableLegacyUnauthenticatedModes(false)
.build();
final String input = "AesCbcV1toV3";
v1Client.putObject(BUCKET, objectKey, input);
assertThrows(S3EncryptionClientException.class, () -> v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey)));
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void AesCbcV1toV3FailsWhenUnauthencticateModeDisabled() {
final String objectKey = appendTestSuffix("fails-aes-cbc-v1-to-v3-when-unauthencticate-mode-disabled");
// V1 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
CryptoConfiguration v1CryptoConfig =
new CryptoConfiguration(CryptoMode.EncryptionOnly);
AmazonS3Encryption v1Client = AmazonS3EncryptionClient.encryptionBuilder()
.withCryptoConfiguration(v1CryptoConfig)
.withEncryptionMaterials(materialsProvider)
.build();
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.enableLegacyWrappingAlgorithms(true)
.enableLegacyUnauthenticatedModes(false)
.build();
// Asserts
final String input = "AesCbcV1toV3";
v1Client.putObject(BUCKET, objectKey, input);
assertThrows(S3EncryptionClientException.class, () -> v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey)));
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void AesCbcV1toV3FailsWhenLegacyKeyringDisabled() {
final String objectKey = appendTestSuffix("fails-aes-cbc-v1-to-v3-when-legacy-keyring-disabled");
// V1 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
CryptoConfiguration v1CryptoConfig =
new CryptoConfiguration(CryptoMode.EncryptionOnly);
AmazonS3Encryption v1Client = AmazonS3EncryptionClient.encryptionBuilder()
.withCryptoConfiguration(v1CryptoConfig)
.withEncryptionMaterials(materialsProvider)
.build();
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.enableLegacyWrappingAlgorithms(false)
.enableLegacyUnauthenticatedModes(true)
.build();
// Asserts
final String input = "AesCbcV1toV3";
v1Client.putObject(BUCKET, objectKey, input);
assertThrows(S3EncryptionClientException.class, () -> v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey)));
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void AesWrapV1toV3FailsWhenLegacyModeDisabled() {
final String objectKey = appendTestSuffix("aes-wrap-v1-to-v3");
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
CryptoConfiguration v1CryptoConfig =
new CryptoConfiguration(CryptoMode.AuthenticatedEncryption);
AmazonS3Encryption v1Client = AmazonS3EncryptionClient.encryptionBuilder()
.withCryptoConfiguration(v1CryptoConfig)
.withEncryptionMaterials(materialsProvider)
.build();
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.enableLegacyWrappingAlgorithms(false)
.build();
final String input = "AesGcmV1toV3";
v1Client.putObject(BUCKET, objectKey, input);
assertThrows(S3EncryptionClientException.class, () -> v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey)));
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
}
| 2,208 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/S3EncryptionClientRsaKeyPairTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.encryption.s3.materials.PartialRsaKeyPair;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.appendTestSuffix;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.deleteObject;
public class S3EncryptionClientRsaKeyPairTest {
private static final String BUCKET = System.getenv("AWS_S3EC_TEST_BUCKET");
private static KeyPair RSA_KEY_PAIR;
@BeforeAll
public static void setUp() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(2048);
RSA_KEY_PAIR = keyPairGen.generateKeyPair();
}
@Test
public void RsaPublicAndPrivateKeys() {
final String objectKey = appendTestSuffix("rsa-public-and-private");
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.rsaKeyPair(RSA_KEY_PAIR)
.build();
// Asserts
final String input = "RsaOaepV3toV3";
v3Client.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), RequestBody.fromString(input));
ResponseBytes<GetObjectResponse> objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey));
String output = objectResponse.asUtf8String();
assertEquals(input, output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void RsaPrivateKeyCanOnlyDecrypt() {
final String objectKey = appendTestSuffix("rsa-private-key-only");
S3Client v3Client = S3EncryptionClient.builder()
.rsaKeyPair(RSA_KEY_PAIR)
.build();
S3Client v3ClientReadOnly = S3EncryptionClient.builder()
.rsaKeyPair(new PartialRsaKeyPair(RSA_KEY_PAIR.getPrivate(), null))
.build();
final String input = "RsaOaepV3toV3";
v3Client.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), RequestBody.fromString(input));
ResponseBytes<GetObjectResponse> objectResponse = v3ClientReadOnly.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey));
String output = objectResponse.asUtf8String();
assertEquals(input, output);
assertThrows(S3EncryptionClientException.class, () -> v3ClientReadOnly.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(input)
.build(), RequestBody.fromString(input)));
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void RsaPublicKeyCanOnlyEncrypt() {
final String objectKey = appendTestSuffix("rsa-public-key-only");
S3Client v3Client = S3EncryptionClient.builder()
.rsaKeyPair(new PartialRsaKeyPair(null, RSA_KEY_PAIR.getPublic()))
.build();
v3Client.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), RequestBody.fromString(objectKey));
assertThrows(S3EncryptionClientException.class, () -> v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey)));
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
}
| 2,209 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/S3EncryptionClientStreamTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3;
import com.amazonaws.services.s3.AmazonS3Encryption;
import com.amazonaws.services.s3.AmazonS3EncryptionClient;
import com.amazonaws.services.s3.model.CryptoConfiguration;
import com.amazonaws.services.s3.model.CryptoMode;
import com.amazonaws.services.s3.model.EncryptionMaterials;
import com.amazonaws.services.s3.model.EncryptionMaterialsProvider;
import com.amazonaws.services.s3.model.StaticEncryptionMaterialsProvider;
import org.apache.commons.io.IOUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.encryption.s3.utils.BoundedStreamBufferer;
import software.amazon.encryption.s3.utils.BoundedInputStream;
import software.amazon.encryption.s3.utils.MarkResetBoundedZerosInputStream;
import software.amazon.encryption.s3.utils.S3EncryptionClientTestResources;
import javax.crypto.AEADBadTagException;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.KMS_KEY_ID;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.appendTestSuffix;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.deleteObject;
/**
* Test the streaming functionality using various stream implementations.
*/
public class S3EncryptionClientStreamTest {
private static final String BUCKET = S3EncryptionClientTestResources.BUCKET;
private static final int DEFAULT_TEST_STREAM_LENGTH = (int) (Math.random() * 10000);
private static SecretKey AES_KEY;
@BeforeAll
public static void setUp() throws NoSuchAlgorithmException {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
AES_KEY = keyGen.generateKey();
}
@Test
public void markResetInputStreamV3Encrypt() throws IOException {
final String objectKey = appendTestSuffix("markResetInputStreamV3Encrypt");
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
final int inputLength = DEFAULT_TEST_STREAM_LENGTH;
final InputStream inputStream = new MarkResetBoundedZerosInputStream(inputLength);
inputStream.mark(inputLength);
final String inputStreamAsUtf8String = IoUtils.toUtf8String(inputStream);
inputStream.reset();
v3Client.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), RequestBody.fromInputStream(inputStream, inputLength));
inputStream.close();
final String actualObject = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.build()).asUtf8String();
assertEquals(inputStreamAsUtf8String, actualObject);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void ordinaryInputStreamV3Encrypt() throws IOException {
final String objectKey = appendTestSuffix("ordinaryInputStreamV3Encrypt");
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
final int inputLength = DEFAULT_TEST_STREAM_LENGTH;
// Create a second stream of zeros because reset is not supported
// and reading into the byte string will consume the stream.
final InputStream inputStream = new BoundedInputStream(inputLength);
final InputStream inputStreamForString = new BoundedInputStream(inputLength);
final String inputStreamAsUtf8String = IoUtils.toUtf8String(inputStreamForString);
v3Client.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), RequestBody.fromInputStream(inputStream, inputLength));
inputStream.close();
final String actualObject = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.build()).asUtf8String();
assertEquals(inputStreamAsUtf8String, actualObject);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void ordinaryInputStreamV3Decrypt() throws IOException {
final String objectKey = appendTestSuffix("ordinaryInputStreamV3Decrypt");
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
final int inputLength = DEFAULT_TEST_STREAM_LENGTH;
// Create a second stream of zeros because reset is not supported
// and reading into the byte string will consume the stream.
final InputStream inputStream = new BoundedInputStream(inputLength);
final InputStream inputStreamForString = new BoundedInputStream(inputLength);
final String inputStreamAsUtf8String = IoUtils.toUtf8String(inputStreamForString);
v3Client.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), RequestBody.fromInputStream(inputStream, inputLength));
inputStream.close();
final ResponseInputStream<GetObjectResponse> responseInputStream = v3Client.getObject(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.build());
final String actualObject = new String(BoundedStreamBufferer.toByteArray(responseInputStream, inputLength / 8),
StandardCharsets.UTF_8);
assertEquals(inputStreamAsUtf8String, actualObject);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void ordinaryInputStreamV3DecryptCbc() throws IOException {
final String objectKey = appendTestSuffix("markResetInputStreamV3DecryptCbc");
// V1 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
CryptoConfiguration v1CryptoConfig =
new CryptoConfiguration(CryptoMode.EncryptionOnly);
AmazonS3Encryption v1Client = AmazonS3EncryptionClient.encryptionBuilder()
.withCryptoConfiguration(v1CryptoConfig)
.withEncryptionMaterials(materialsProvider)
.build();
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.enableLegacyWrappingAlgorithms(true)
.enableLegacyUnauthenticatedModes(true)
.build();
final int inputLength = DEFAULT_TEST_STREAM_LENGTH;
final InputStream inputStreamForString = new BoundedInputStream(inputLength);
final String inputStreamAsUtf8String = IoUtils.toUtf8String(inputStreamForString);
v1Client.putObject(BUCKET, objectKey, inputStreamAsUtf8String);
final ResponseInputStream<GetObjectResponse> responseInputStream = v3Client.getObject(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.build());
final String actualObject = new String(BoundedStreamBufferer.toByteArray(responseInputStream, inputLength / 8),
StandardCharsets.UTF_8);
assertEquals(inputStreamAsUtf8String, actualObject);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void invalidBufferSize() {
assertThrows(S3EncryptionClientException.class, () -> S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.setBufferSize(15L)
.build());
assertThrows(S3EncryptionClientException.class, () -> S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.setBufferSize(68719476705L)
.build());
assertThrows(S3EncryptionClientException.class, () -> S3AsyncEncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.setBufferSize(15L)
.build());
assertThrows(S3EncryptionClientException.class, () -> S3AsyncEncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.setBufferSize(68719476705L)
.build());
}
@Test
public void failsWhenBothBufferSizeAndDelayedAuthModeEnabled() {
assertThrows(S3EncryptionClientException.class, () -> S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.setBufferSize(16)
.enableDelayedAuthenticationMode(true)
.build());
assertThrows(S3EncryptionClientException.class, () -> S3AsyncEncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.setBufferSize(16)
.enableDelayedAuthenticationMode(true)
.build());
}
@Test
public void customSetBufferSizeWithLargeObject() throws IOException {
final String objectKey = appendTestSuffix("large-object-test-custom-buffer-size");
Security.addProvider(new BouncyCastleProvider());
Provider provider = Security.getProvider("BC");
// V3 Client with custom max buffer size 32 MiB.
S3Client v3ClientWithBuffer32MiB = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.cryptoProvider(provider)
.setBufferSize(32 * 1024 * 1024)
.build();
// V3 Client with default buffer size (i.e. 64MiB)
// When enableDelayedAuthenticationMode is set to true, delayed authentication mode always takes priority over buffered mode.
S3Client v3ClientWithDelayedAuth = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.cryptoProvider(provider)
.enableDelayedAuthenticationMode(true)
.build();
// Tight bound on the custom buffer size limit of 32MiB
final long fileSizeExceedingDefaultLimit = 1024 * 1024 * 32 + 1;
final InputStream largeObjectStream = new BoundedInputStream(fileSizeExceedingDefaultLimit);
v3ClientWithBuffer32MiB.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), RequestBody.fromInputStream(largeObjectStream, fileSizeExceedingDefaultLimit));
largeObjectStream.close();
// Object is larger than Buffer, so getObject fails
assertThrows(S3EncryptionClientException.class, () -> v3ClientWithBuffer32MiB.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey)));
// You have to either enable the delayed auth mode or increase max buffer size (but in allowed bounds)
ResponseInputStream<GetObjectResponse> response = v3ClientWithDelayedAuth.getObject(builder -> builder
.bucket(BUCKET)
.key(objectKey));
assertTrue(IOUtils.contentEquals(new BoundedInputStream(fileSizeExceedingDefaultLimit), response));
response.close();
// Cleanup
deleteObject(BUCKET, objectKey, v3ClientWithBuffer32MiB);
v3ClientWithBuffer32MiB.close();
v3ClientWithDelayedAuth.close();
}
@Test
public void customSetBufferSizeWithLargeObjectAsyncClient() throws IOException {
final String objectKey = appendTestSuffix("large-object-test-custom-buffer-size-async");
Security.addProvider(new BouncyCastleProvider());
Provider provider = Security.getProvider("BC");
// V3 Client with custom max buffer size 32 MiB.
S3AsyncClient v3ClientWithBuffer32MiB = S3AsyncEncryptionClient.builder()
.aesKey(AES_KEY)
.cryptoProvider(provider)
.setBufferSize(32 * 1024 * 1024)
.build();
// V3 Client with default buffer size (i.e. 64MiB)
// When enableDelayedAuthenticationMode is set to true, delayed authentication mode always takes priority over buffered mode.
S3AsyncClient v3ClientWithDelayedAuth = S3AsyncEncryptionClient.builder()
.aesKey(AES_KEY)
.cryptoProvider(provider)
.enableDelayedAuthenticationMode(true)
.build();
// Tight bound on the custom buffer size limit of 32MiB
final long fileSizeExceedingDefaultLimit = 1024 * 1024 * 32 + 1;
final InputStream largeObjectStream = new BoundedInputStream(fileSizeExceedingDefaultLimit);
CompletableFuture<PutObjectResponse> futurePut = v3ClientWithBuffer32MiB.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), AsyncRequestBody.fromInputStream(largeObjectStream, fileSizeExceedingDefaultLimit, Executors.newSingleThreadExecutor()));
futurePut.join();
largeObjectStream.close();
try {
// Object is larger than Buffer, so getObject fails
CompletableFuture<ResponseInputStream<GetObjectResponse>> futureResponse = v3ClientWithBuffer32MiB.getObject(builder -> builder
.bucket(BUCKET)
.key(objectKey), AsyncResponseTransformer.toBlockingInputStream());
futureResponse.join();
} catch (CompletionException e) {
assertEquals(S3EncryptionClientException.class, e.getCause().getClass());
}
// You have to either enable the delayed auth mode or increase max buffer size (but in allowed bounds)
CompletableFuture<ResponseInputStream<GetObjectResponse>> futureGet = v3ClientWithDelayedAuth.getObject(builder -> builder
.bucket(BUCKET)
.key(objectKey), AsyncResponseTransformer.toBlockingInputStream());
ResponseInputStream<GetObjectResponse> output = futureGet.join();
assertTrue(IOUtils.contentEquals(new BoundedInputStream(fileSizeExceedingDefaultLimit), output));
output.close();
// Cleanup
deleteObject(BUCKET, objectKey, v3ClientWithBuffer32MiB);
v3ClientWithBuffer32MiB.close();
v3ClientWithDelayedAuth.close();
}
@Test
public void delayedAuthModeWithLargeObject() throws IOException {
final String objectKey = appendTestSuffix("large-object-test");
Security.addProvider(new BouncyCastleProvider());
Provider provider = Security.getProvider("BC");
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.cryptoProvider(provider)
.build();
// Tight bound on the default limit of 64MiB
final long fileSizeExceedingDefaultLimit = 1024 * 1024 * 64 + 1;
final InputStream largeObjectStream = new BoundedInputStream(fileSizeExceedingDefaultLimit);
v3Client.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), RequestBody.fromInputStream(largeObjectStream, fileSizeExceedingDefaultLimit));
largeObjectStream.close();
// Delayed Authentication is not enabled, so getObject fails
assertThrows(S3EncryptionClientException.class, () -> v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey)));
S3Client v3ClientWithDelayedAuth = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.enableDelayedAuthenticationMode(true)
.build();
// Once enabled, the getObject request passes
ResponseInputStream<GetObjectResponse> response = v3ClientWithDelayedAuth.getObject(builder -> builder
.bucket(BUCKET)
.key(objectKey));
assertTrue(IOUtils.contentEquals(new BoundedInputStream(fileSizeExceedingDefaultLimit), response));
response.close();
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void delayedAuthModeWithLargerThanMaxObjectFails() throws IOException {
final String objectKey = appendTestSuffix("larger-than-max-object-delayed-auth-mode");
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.enableDelayedAuthenticationMode(true)
.build();
final long fileSizeExceedingGCMLimit = (1L << 39) - 256 / 8;
final InputStream largeObjectStream = new BoundedInputStream(fileSizeExceedingGCMLimit);
assertThrows(S3EncryptionClientException.class, () -> v3Client.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), RequestBody.fromInputStream(largeObjectStream, fileSizeExceedingGCMLimit)));
largeObjectStream.close();
// Cleanup
v3Client.close();
}
@Test
public void AesGcmV3toV3StreamWithTamperedTag() {
final String objectKey = appendTestSuffix("aes-gcm-v3-to-v3-stream-tamper-tag");
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
// 640 bytes of gibberish - enough to cover multiple blocks
final String input = "1esAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYo"
+ "2esAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYo"
+ "3esAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYo"
+ "4esAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYo"
+ "5esAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYo"
+ "6esAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYo"
+ "7esAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYo"
+ "8esAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYo"
+ "9esAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYo"
+ "10sAAAYoAesAAAEndOfChunkAesAAAYoAesAAAYoAesAAAYoAesAAAYoAesAAAYo";
final int inputLength = input.length();
v3Client.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), RequestBody.fromString(input));
// Use an unencrypted (plaintext) client to interact with the encrypted object
final S3Client plaintextS3Client = S3Client.builder().build();
ResponseBytes<GetObjectResponse> objectResponse = plaintextS3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey));
final byte[] encryptedBytes = objectResponse.asByteArray();
final int tagLength = 16;
final byte[] tamperedBytes = new byte[inputLength + tagLength];
// Copy the enciphered bytes
System.arraycopy(encryptedBytes, 0, tamperedBytes, 0, inputLength);
final byte[] tamperedTag = new byte[tagLength];
// Increment the first byte of the tag
tamperedTag[0] = (byte) (encryptedBytes[inputLength + 1] + 1);
// Copy the rest of the tag as-is
System.arraycopy(encryptedBytes, inputLength + 1, tamperedTag, 1, tagLength - 1);
// Append the tampered tag
System.arraycopy(tamperedTag, 0, tamperedBytes, inputLength, tagLength);
// Sanity check that the objects differ
assertNotEquals(encryptedBytes, tamperedBytes);
// Replace the encrypted object with the tampered object
PutObjectRequest tamperedPut = PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.metadata(objectResponse.response().metadata()) // Preserve metadata from encrypted object
.build();
plaintextS3Client.putObject(tamperedPut, RequestBody.fromBytes(tamperedBytes));
// Get (and decrypt) the (modified) object from S3
ResponseInputStream<GetObjectResponse> dataStream = v3Client.getObject(builder -> builder
.bucket(BUCKET)
.key(objectKey));
final int chunkSize = 300;
final byte[] chunk1 = new byte[chunkSize];
// Stream decryption will throw an exception on the first byte read
try {
dataStream.read(chunk1, 0, chunkSize);
} catch (RuntimeException outerEx) {
assertTrue(outerEx.getCause() instanceof AEADBadTagException);
} catch (IOException unexpected) {
// Not expected, but fail the test anyway
fail(unexpected);
}
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
}
| 2,210 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/S3EncryptionClientTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3;
import com.amazonaws.services.s3.AmazonS3EncryptionClientV2;
import com.amazonaws.services.s3.AmazonS3EncryptionV2;
import com.amazonaws.services.s3.model.CryptoConfigurationV2;
import com.amazonaws.services.s3.model.CryptoMode;
import com.amazonaws.services.s3.model.CryptoStorageMode;
import com.amazonaws.services.s3.model.EncryptionMaterials;
import com.amazonaws.services.s3.model.EncryptionMaterialsProvider;
import com.amazonaws.services.s3.model.StaticEncryptionMaterialsProvider;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.NoSuchBucketException;
import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
import software.amazon.awssdk.services.s3.model.NoSuchUploadException;
import software.amazon.awssdk.services.s3.model.ObjectIdentifier;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.encryption.s3.materials.CryptographicMaterialsManager;
import software.amazon.encryption.s3.materials.DefaultCryptoMaterialsManager;
import software.amazon.encryption.s3.materials.KmsKeyring;
import software.amazon.encryption.s3.utils.BoundedInputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Security;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.withSettings;
import static software.amazon.encryption.s3.S3EncryptionClient.withAdditionalConfiguration;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.BUCKET;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.KMS_KEY_ALIAS;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.KMS_KEY_ID;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.appendTestSuffix;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.deleteObject;
/**
* This class is an integration test for verifying behavior of the V3 client
* under various scenarios.
*/
public class S3EncryptionClientTest {
private static SecretKey AES_KEY;
private static KeyPair RSA_KEY_PAIR;
@BeforeAll
public static void setUp() throws NoSuchAlgorithmException {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
AES_KEY = keyGen.generateKey();
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(2048);
RSA_KEY_PAIR = keyPairGen.generateKeyPair();
}
@Test
public void copyObjectTransparently() {
final String objectKey = appendTestSuffix("copy-object-from-here");
final String newObjectKey = appendTestSuffix("copy-object-to-here");
S3Client s3EncryptionClient = S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.build();
final String input = "SimpleTestOfV3EncryptionClientCopyObject";
s3EncryptionClient.putObject(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.build(),
RequestBody.fromString(input));
s3EncryptionClient.copyObject(builder -> builder
.sourceBucket(BUCKET)
.destinationBucket(BUCKET)
.sourceKey(objectKey)
.destinationKey(newObjectKey)
.build());
ResponseBytes<GetObjectResponse> objectResponse = s3EncryptionClient.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(newObjectKey)
.build());
String output = objectResponse.asUtf8String();
assertEquals(input, output);
// Cleanup
deleteObject(BUCKET, objectKey, s3EncryptionClient);
deleteObject(BUCKET, newObjectKey, s3EncryptionClient);
s3EncryptionClient.close();
}
@Test
public void deleteObjectWithInstructionFileSuccess() {
final String objectKey = appendTestSuffix("delete-object-with-instruction-file");
// V2 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
CryptoConfigurationV2 cryptoConfig =
new CryptoConfigurationV2(CryptoMode.StrictAuthenticatedEncryption)
.withStorageMode(CryptoStorageMode.InstructionFile);
AmazonS3EncryptionV2 v2Client = AmazonS3EncryptionClientV2.encryptionBuilder()
.withCryptoConfiguration(cryptoConfig)
.withEncryptionMaterialsProvider(materialsProvider)
.build();
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
final String input = "DeleteObjectWithInstructionFileSuccess";
v2Client.putObject(BUCKET, objectKey, input);
// Delete Object
v3Client.deleteObject(builder -> builder.bucket(BUCKET).key(objectKey));
S3Client s3Client = S3Client.builder().build();
// Assert throw NoSuchKeyException when getObject for objectKey
assertThrows(S3Exception.class, () -> s3Client.getObject(builder -> builder
.bucket(BUCKET)
.key(objectKey)));
assertThrows(S3Exception.class, () -> s3Client.getObject(builder -> builder
.bucket(BUCKET)
.key(objectKey + ".instruction")));
// Cleanup
v3Client.close();
s3Client.close();
}
@Test
public void deleteObjectsWithInstructionFilesSuccess() {
final String[] objectKeys = {appendTestSuffix("delete-object-with-instruction-file-1"),
appendTestSuffix("delete-object-with-instruction-file-2"),
appendTestSuffix("delete-object-with-instruction-file-3")};
// V2 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
CryptoConfigurationV2 cryptoConfig =
new CryptoConfigurationV2(CryptoMode.StrictAuthenticatedEncryption)
.withStorageMode(CryptoStorageMode.InstructionFile);
AmazonS3EncryptionV2 v2Client = AmazonS3EncryptionClientV2.encryptionBuilder()
.withCryptoConfiguration(cryptoConfig)
.withEncryptionMaterialsProvider(materialsProvider)
.build();
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
final String input = "DeleteObjectsWithInstructionFileSuccess";
List<ObjectIdentifier> objects = new ArrayList<>();
for (String objectKey : objectKeys) {
v2Client.putObject(BUCKET, objectKey, input);
objects.add(ObjectIdentifier.builder().key(objectKey).build());
}
// Delete Objects from S3 Buckets
v3Client.deleteObjects(builder -> builder
.bucket(BUCKET)
.delete(builder1 -> builder1.objects(objects)));
S3Client s3Client = S3Client.builder().build();
// Assert throw NoSuchKeyException when getObject for any of objectKeys
assertThrows(S3Exception.class, () -> s3Client.getObject(builder -> builder
.bucket(BUCKET)
.key(objectKeys[0])));
assertThrows(S3Exception.class, () -> s3Client.getObject(builder -> builder
.bucket(BUCKET)
.key(objectKeys[0] + ".instruction")));
// Cleanup
v3Client.close();
s3Client.close();
}
@Test
public void deleteObjectWithWrongObjectKeySuccess() {
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
assertDoesNotThrow(() -> v3Client.deleteObject(builder -> builder.bucket(BUCKET).key("InvalidKey")));
// Cleanup
v3Client.close();
}
@Test
public void deleteObjectWithWrongBucketFailure() {
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
try {
v3Client.deleteObject(builder -> builder.bucket("NotMyBukkit").key("InvalidKey"));
} catch (S3EncryptionClientException exception) {
// Verify inner exception
assertTrue(exception.getCause() instanceof NoSuchBucketException);
}
v3Client.close();
}
@Test
public void deleteObjectsWithWrongBucketFailure() {
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
List<ObjectIdentifier> objects = new ArrayList<>();
objects.add(ObjectIdentifier.builder().key("InvalidKey").build());
try {
v3Client.deleteObjects(builder -> builder.bucket("NotMyBukkit").delete(builder1 -> builder1.objects(objects)));
} catch (S3EncryptionClientException exception) {
// Verify inner exception
assertTrue(exception.getCause() instanceof NoSuchBucketException);
}
v3Client.close();
}
@Test
public void getNonExistentObject() {
final String objectKey = appendTestSuffix("this-is-not-an-object-key");
S3Client v3Client = S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ALIAS)
.build();
// Ensure the object does not exist
deleteObject(BUCKET, objectKey, v3Client);
try {
v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.build());
} catch (S3EncryptionClientException exception) {
// Depending on the permissions of the calling principal,
// this could be NoSuchKeyException
// or S3Exception (access denied)
assertTrue(exception.getCause() instanceof S3Exception);
}
// Cleanup
v3Client.close();
}
@Test
public void s3EncryptionClientWithMultipleKeyringsFails() {
assertThrows(S3EncryptionClientException.class, () -> S3EncryptionClient.builder()
.aesKey(AES_KEY)
.rsaKeyPair(RSA_KEY_PAIR)
.build());
}
@Test
public void s3EncryptionClientWithNoKeyringsFails() {
assertThrows(S3EncryptionClientException.class, () -> S3EncryptionClient.builder()
.build());
}
@Test
public void s3EncryptionClientWithNoLegacyKeyringsFails() {
assertThrows(S3EncryptionClientException.class, () -> S3EncryptionClient.builder()
.enableLegacyWrappingAlgorithms(true)
.build());
}
@Test
public void KmsWithAliasARN() {
final String objectKey = appendTestSuffix("kms-with-alias-arn");
S3Client v3Client = S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ALIAS)
.build();
simpleV3RoundTrip(v3Client, objectKey);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void KmsWithShortKeyId() {
final String objectKey = appendTestSuffix("kms-with-short-key-id");
// Just assume the ARN is well-formed
// Also assume that the region is set correctly
final String shortId = KMS_KEY_ID.split("/")[1];
S3Client v3Client = S3EncryptionClient.builder()
.kmsKeyId(shortId)
.build();
simpleV3RoundTrip(v3Client, objectKey);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void KmsAliasARNToKeyId() {
final String objectKey = appendTestSuffix("kms-alias-arn-to-key-id");
S3Client aliasClient = S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ALIAS)
.build();
S3Client keyIdClient = S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.build();
final String input = "KmsAliasARNToKeyId";
Map<String, String> encryptionContext = new HashMap<>();
encryptionContext.put("user-metadata-key", "user-metadata-value-alias-to-id");
aliasClient.putObject(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.overrideConfiguration(withAdditionalConfiguration(encryptionContext)),
RequestBody.fromString(input));
ResponseBytes<GetObjectResponse> objectResponse = keyIdClient.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.overrideConfiguration(withAdditionalConfiguration(encryptionContext)));
String output = objectResponse.asUtf8String();
assertEquals(input, output);
deleteObject(BUCKET, objectKey, aliasClient);
aliasClient.close();
keyIdClient.close();
}
@Test
public void AesKeyringWithInvalidAesKey() throws NoSuchAlgorithmException {
SecretKey invalidAesKey;
KeyGenerator keyGen = KeyGenerator.getInstance("DES");
keyGen.init(56);
invalidAesKey = keyGen.generateKey();
assertThrows(S3EncryptionClientException.class, () -> S3EncryptionClient.builder()
.aesKey(invalidAesKey)
.build());
}
@Test
public void RsaKeyringWithInvalidRsaKey() throws NoSuchAlgorithmException {
KeyPair invalidRsaKey;
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("EC");
keyPairGen.initialize(256);
invalidRsaKey = keyPairGen.generateKeyPair();
assertThrows(S3EncryptionClientException.class, () -> S3EncryptionClient.builder()
.rsaKeyPair(invalidRsaKey)
.build());
}
@Test
public void s3EncryptionClientWithKeyringFromKmsKeyIdSucceeds() {
final String objectKey = appendTestSuffix("keyring-from-kms-key-id");
KmsKeyring keyring = KmsKeyring.builder().wrappingKeyId(KMS_KEY_ID).build();
S3Client v3Client = S3EncryptionClient.builder()
.keyring(keyring)
.build();
simpleV3RoundTrip(v3Client, objectKey);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void s3EncryptionClientWithCmmFromKmsKeyIdSucceeds() {
final String objectKey = appendTestSuffix("cmm-from-kms-key-id");
KmsKeyring keyring = KmsKeyring.builder().wrappingKeyId(KMS_KEY_ID).build();
CryptographicMaterialsManager cmm = DefaultCryptoMaterialsManager.builder()
.keyring(keyring)
.build();
S3Client v3Client = S3EncryptionClient.builder()
.cryptoMaterialsManager(cmm)
.build();
simpleV3RoundTrip(v3Client, objectKey);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void s3EncryptionClientWithWrappedS3ClientSucceeds() {
final String objectKey = appendTestSuffix("wrapped-s3-client-with-kms-key-id");
S3Client wrappedClient = S3Client.create();
S3AsyncClient wrappedAsyncClient = S3AsyncClient.create();
S3Client wrappingClient = S3EncryptionClient.builder()
.wrappedClient(wrappedClient)
.wrappedAsyncClient(wrappedAsyncClient)
.kmsKeyId(KMS_KEY_ID)
.build();
simpleV3RoundTrip(wrappingClient, objectKey);
// Cleanup
deleteObject(BUCKET, objectKey, wrappingClient);
wrappedClient.close();
wrappedAsyncClient.close();
wrappingClient.close();
}
/**
* S3EncryptionClient implements S3Client, so it can be passed into the builder as a wrappedClient.
* However, is not a supported use case, and the builder should throw an exception if this happens.
*/
@Test
public void s3EncryptionClientWithWrappedS3EncryptionClientFails() {
S3AsyncClient wrappedAsyncClient = S3AsyncEncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.build();
assertThrows(S3EncryptionClientException.class, () -> S3EncryptionClient.builder()
.wrappedAsyncClient(wrappedAsyncClient)
.kmsKeyId(KMS_KEY_ID)
.build());
}
@Test
public void s3EncryptionClientWithNullSecureRandomFails() {
assertThrows(S3EncryptionClientException.class, () -> S3EncryptionClient.builder()
.aesKey(AES_KEY)
.secureRandom(null)
.build());
}
@Test
public void s3EncryptionClientFromKMSKeyDoesNotUseUnprovidedSecureRandom() {
SecureRandom mockSecureRandom = mock(SecureRandom.class, withSettings().withoutAnnotations());
final String objectKey = appendTestSuffix("no-secure-random-object-kms");
S3Client v3Client = S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.build();
simpleV3RoundTrip(v3Client, objectKey);
verify(mockSecureRandom, never()).nextBytes(any());
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void cryptoProviderV3toV3Enabled() {
final String objectKey = appendTestSuffix("crypto-provider-enabled-v3-to-v3");
Security.addProvider(new BouncyCastleProvider());
Provider provider = Security.getProvider("BC");
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.cryptoProvider(provider)
.build();
final String input = "CryptoProviderEnabled";
v3Client.putObject(builder -> builder
.bucket(BUCKET)
.key(objectKey), RequestBody.fromString(input));
ResponseBytes<GetObjectResponse> objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey));
String output = objectResponse.asUtf8String();
assertEquals(input, output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void cryptoProviderV2toV3Enabled() {
final String objectKey = appendTestSuffix("crypto-provider-enabled-v2-to-v3");
Security.addProvider(new BouncyCastleProvider());
Provider provider = Security.getProvider("BC");
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
CryptoConfigurationV2 v2Config = new CryptoConfigurationV2()
.withCryptoProvider(provider)
.withAlwaysUseCryptoProvider(true);
AmazonS3EncryptionV2 v2Client = AmazonS3EncryptionClientV2.encryptionBuilder()
.withEncryptionMaterialsProvider(materialsProvider)
.withCryptoConfiguration(v2Config)
.build();
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.cryptoProvider(provider)
.build();
final String input = "CryptoProviderEnabled";
v2Client.putObject(BUCKET, objectKey, input);
ResponseBytes<GetObjectResponse> objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey));
String output = objectResponse.asUtf8String();
assertEquals(input, output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void contentLengthRequest() {
final String objectKey = appendTestSuffix("content-length");
S3Client s3EncryptionClient = S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.build();
final String input = "SimpleTestOfV3EncryptionClientCopyObject";
final int inputLength = input.length();
s3EncryptionClient.putObject(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.contentLength((long) inputLength)
.build(),
RequestBody.fromString(input));
ResponseBytes<GetObjectResponse> objectResponse = s3EncryptionClient.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.build());
String output = objectResponse.asUtf8String();
assertEquals(input, output);
// Cleanup
deleteObject(BUCKET, objectKey, s3EncryptionClient);
s3EncryptionClient.close();
}
@Test
public void attemptToDecryptPlaintext() {
final String objectKey = appendTestSuffix("plaintext-object");
final S3Client plaintextS3Client = S3Client.builder().build();
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
final String input = "SomePlaintext";
plaintextS3Client.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), RequestBody.fromString(input));
// Attempt to get (and decrypt) the (plaintext) object from S3
assertThrows(S3EncryptionClientException.class, () -> v3Client.getObject(builder -> builder
.bucket(BUCKET)
.key(objectKey)));
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void createMultipartUploadFailure() {
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
try {
v3Client.createMultipartUpload(builder -> builder.bucket("NotMyBukkit").key("InvalidKey").build());
} catch (S3EncryptionClientException exception) {
// Verify inner exception
assertInstanceOf(NoSuchBucketException.class, exception.getCause());
}
v3Client.close();
}
@Test
public void uploadPartFailure() {
final String objectKey = appendTestSuffix("upload-part-failure");
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
// To get a server-side failure from uploadPart,
// a valid MPU request must be created
CreateMultipartUploadResponse initiateResult = v3Client.createMultipartUpload(builder ->
builder.bucket(BUCKET).key(objectKey));
try {
v3Client.uploadPart(builder -> builder.partNumber(1).bucket("NotMyBukkit").key("InvalidKey").uploadId(initiateResult.uploadId()).build(),
RequestBody.fromInputStream(new BoundedInputStream(16), 16));
} catch (S3EncryptionClientException exception) {
// Verify inner exception
assertInstanceOf(NoSuchBucketException.class, exception.getCause());
}
// MPU was not completed, but abort and delete to be safe
v3Client.abortMultipartUpload(builder -> builder.bucket(BUCKET).key(objectKey).uploadId(initiateResult.uploadId()).build());
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void completeMultipartUploadFailure() {
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
try {
v3Client.completeMultipartUpload(builder -> builder.bucket("NotMyBukkit").key("InvalidKey").uploadId("Invalid").build());
} catch (S3EncryptionClientException exception) {
// Verify inner exception
assertInstanceOf(NoSuchBucketException.class, exception.getCause());
}
v3Client.close();
}
@Test
public void abortMultipartUploadFailure() {
final String objectKey = appendTestSuffix("abort-multipart-failure");
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
try {
v3Client.abortMultipartUpload(builder -> builder.bucket(BUCKET).key(objectKey).uploadId("invalid upload id").build());
} catch (S3EncryptionClientException exception) {
// Verify inner exception
assertInstanceOf(NoSuchUploadException.class, exception.getCause());
}
v3Client.close();
}
/**
* A simple, reusable round-trip (encryption + decryption) using a given
* S3Client. Useful for testing client configuration.
*
* @param v3Client the client under test
*/
private void simpleV3RoundTrip(final S3Client v3Client, final String objectKey) {
final String input = "SimpleTestOfV3EncryptionClient";
v3Client.putObject(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.build(),
RequestBody.fromString(input));
ResponseBytes<GetObjectResponse> objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.build());
String output = objectResponse.asUtf8String();
assertEquals(input, output);
}
}
| 2,211 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/S3EncryptionClientRangedGetCompatibilityTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3;
import com.amazonaws.services.s3.AmazonS3Encryption;
import com.amazonaws.services.s3.AmazonS3EncryptionClient;
import com.amazonaws.services.s3.model.CryptoConfiguration;
import com.amazonaws.services.s3.model.EncryptionMaterials;
import com.amazonaws.services.s3.model.EncryptionMaterialsProvider;
import com.amazonaws.services.s3.model.StaticEncryptionMaterialsProvider;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.CompletionException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.BUCKET;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.appendTestSuffix;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.deleteObject;
/**
* This class is an integration test for Unauthenticated Ranged Get for AES/CBC and AES/GCM modes
*/
public class S3EncryptionClientRangedGetCompatibilityTest {
private static SecretKey AES_KEY;
@BeforeAll
public static void setUp() throws NoSuchAlgorithmException {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
AES_KEY = keyGen.generateKey();
}
@Test
public void AsyncAesGcmV3toV3RangedGet() {
final String objectKey = appendTestSuffix("async-aes-gcm-v3-to-v3-ranged-get");
final String input = "0bcdefghijklmnopqrst0BCDEFGHIJKLMNOPQRST" +
"1bcdefghijklmnopqrst1BCDEFGHIJKLMNOPQRST" +
"2bcdefghijklmnopqrst2BCDEFGHIJKLMNOPQRST" +
"3bcdefghijklmnopqrst3BCDEFGHIJKLMNOPQRST" +
"4bcdefghijklmnopqrst4BCDEFGHIJKLMNOPQRST";
// Async Client
S3AsyncClient asyncClient = S3AsyncEncryptionClient.builder()
.aesKey(AES_KEY)
.enableLegacyUnauthenticatedModes(true)
.build();
asyncClient.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), AsyncRequestBody.fromString(input)).join();
// Valid Range
ResponseBytes<GetObjectResponse> objectResponse = asyncClient.getObject(builder -> builder
.bucket(BUCKET)
.range("bytes=10-20")
.key(objectKey), AsyncResponseTransformer.toBytes()).join();
String output = objectResponse.asUtf8String();
assertEquals("klmnopqrst0", output);
// Valid start index within input and end index out of range, returns object from start index to End of Stream
objectResponse = asyncClient.getObject(builder -> builder
.bucket(BUCKET)
.range("bytes=190-300")
.key(objectKey), AsyncResponseTransformer.toBytes()).join();
output = objectResponse.asUtf8String();
assertEquals("KLMNOPQRST", output);
// Invalid range start index range greater than ending index, returns entire object
objectResponse = asyncClient.getObject(builder -> builder
.bucket(BUCKET)
.range("bytes=100-50")
.key(objectKey), AsyncResponseTransformer.toBytes()).join();
output = objectResponse.asUtf8String();
assertEquals(input, output);
// Invalid range format, returns entire object
objectResponse = asyncClient.getObject(builder -> builder
.bucket(BUCKET)
.range("10-20")
.key(objectKey), AsyncResponseTransformer.toBytes()).join();
output = objectResponse.asUtf8String();
assertEquals(input, output);
// Invalid range starting index and ending index greater than object length but within Cipher Block size, returns empty object
objectResponse = asyncClient.getObject(builder -> builder
.bucket(BUCKET)
.range("bytes=216-217")
.key(objectKey), AsyncResponseTransformer.toBytes()).join();
output = objectResponse.asUtf8String();
assertEquals("", output);
// Cleanup
deleteObject(BUCKET, objectKey, asyncClient);
asyncClient.close();
}
@Test
public void AsyncFailsOnRangeWhenLegacyModeDisabled() {
final String objectKey = appendTestSuffix("fails-when-on-range-when-legacy-disabled");
final String input = "0bcdefghijklmnopqrst0BCDEFGHIJKLMNOPQRST" +
"1bcdefghijklmnopqrst1BCDEFGHIJKLMNOPQRST" +
"2bcdefghijklmnopqrst2BCDEFGHIJKLMNOPQRST" +
"3bcdefghijklmnopqrst3BCDEFGHIJKLMNOPQRST" +
"4bcdefghijklmnopqrst4BCDEFGHIJKLMNOPQRST";
// V3 Client
S3AsyncClient asyncClient = S3AsyncEncryptionClient.builder()
.aesKey(AES_KEY)
.build();
asyncClient.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), AsyncRequestBody.fromString(input)).join();
assertThrows(S3EncryptionClientException.class, () -> asyncClient.getObject(builder -> builder
.bucket(BUCKET)
.range("bytes=10-20")
.key(objectKey), AsyncResponseTransformer.toBytes()).join());
// Cleanup
deleteObject(BUCKET, objectKey, asyncClient);
asyncClient.close();
}
@Test
public void AsyncAesCbcV1toV3RangedGet() {
final String objectKey = appendTestSuffix("aes-cbc-v1-to-v3-ranged-get-async");
// V1 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
CryptoConfiguration v1CryptoConfig =
new CryptoConfiguration();
AmazonS3Encryption v1Client = AmazonS3EncryptionClient.encryptionBuilder()
.withCryptoConfiguration(v1CryptoConfig)
.withEncryptionMaterials(materialsProvider)
.build();
final String input = "0bcdefghijklmnopqrst0BCDEFGHIJKLMNOPQRST" +
"1bcdefghijklmnopqrst1BCDEFGHIJKLMNOPQRST" +
"2bcdefghijklmnopqrst2BCDEFGHIJKLMNOPQRST" +
"3bcdefghijklmnopqrst3BCDEFGHIJKLMNOPQRST" +
"4bcdefghijklmnopqrst4BCDEFGHIJKLMNOPQRST";
v1Client.putObject(BUCKET, objectKey, input);
// V3 Client
S3AsyncClient v3Client = S3AsyncEncryptionClient.builder()
.aesKey(AES_KEY)
.enableLegacyWrappingAlgorithms(true)
.enableLegacyUnauthenticatedModes(true)
.build();
// Valid Range
ResponseBytes<GetObjectResponse> objectResponse;
objectResponse = v3Client.getObject(builder -> builder
.bucket(BUCKET)
.range("bytes=10-20")
.key(objectKey), AsyncResponseTransformer.toBytes()).join();
String output;
output = objectResponse.asUtf8String();
assertEquals("klmnopqrst0", output);
// Valid start index within input and end index out of range, returns object from start index to End of Stream
objectResponse = v3Client.getObject(builder -> builder
.bucket(BUCKET)
.range("bytes=190-300")
.key(objectKey), AsyncResponseTransformer.toBytes()).join();
output = objectResponse.asUtf8String();
assertEquals("KLMNOPQRST", output);
// Invalid range start index range greater than ending index, returns entire object
objectResponse = v3Client.getObject(builder -> builder
.bucket(BUCKET)
.range("bytes=100-50")
.key(objectKey), AsyncResponseTransformer.toBytes()).join();
output = objectResponse.asUtf8String();
assertEquals(input, output);
// Invalid range format, returns entire object
objectResponse = v3Client.getObject(builder -> builder
.bucket(BUCKET)
.range("10-20")
.key(objectKey), AsyncResponseTransformer.toBytes()).join();
output = objectResponse.asUtf8String();
assertEquals(input, output);
// Invalid range starting index and ending index greater than object length but within Cipher Block size, returns empty object
objectResponse = v3Client.getObject(builder -> builder
.bucket(BUCKET)
.range("bytes=216-217")
.key(objectKey), AsyncResponseTransformer.toBytes()).join();
output = objectResponse.asUtf8String();
assertEquals("", output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void failsOnRangeWhenLegacyModeDisabled() {
final String objectKey = appendTestSuffix("fails-when-on-range-when-legacy-disabled");
final String input = "0bcdefghijklmnopqrst0BCDEFGHIJKLMNOPQRST" +
"1bcdefghijklmnopqrst1BCDEFGHIJKLMNOPQRST" +
"2bcdefghijklmnopqrst2BCDEFGHIJKLMNOPQRST" +
"3bcdefghijklmnopqrst3BCDEFGHIJKLMNOPQRST" +
"4bcdefghijklmnopqrst4BCDEFGHIJKLMNOPQRST";
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
v3Client.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), RequestBody.fromString(input));
// Asserts
assertThrows(S3EncryptionClientException.class, () -> v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.range("bytes=10-20")));
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void AesGcmV3toV3RangedGet() {
final String objectKey = appendTestSuffix("aes-gcm-v3-to-v3-ranged-get");
final String input = "0bcdefghijklmnopqrst0BCDEFGHIJKLMNOPQRST" +
"1bcdefghijklmnopqrst1BCDEFGHIJKLMNOPQRST" +
"2bcdefghijklmnopqrst2BCDEFGHIJKLMNOPQRST" +
"3bcdefghijklmnopqrst3BCDEFGHIJKLMNOPQRST" +
"4bcdefghijklmnopqrst4BCDEFGHIJKLMNOPQRST";
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.enableLegacyUnauthenticatedModes(true)
.build();
v3Client.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), RequestBody.fromString(input));
// Valid Range
ResponseBytes<GetObjectResponse> objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("bytes=10-20")
.key(objectKey));
String output = objectResponse.asUtf8String();
assertEquals("klmnopqrst0", output);
// Valid start index within input and end index out of range, returns object from start index to End of Stream
objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("bytes=190-300")
.key(objectKey));
output = objectResponse.asUtf8String();
assertEquals("KLMNOPQRST", output);
// Invalid range start index range greater than ending index, returns entire object
objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("bytes=100-50")
.key(objectKey));
output = objectResponse.asUtf8String();
assertEquals(input, output);
// Invalid range format, returns entire object
objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("10-20")
.key(objectKey));
output = objectResponse.asUtf8String();
assertEquals(input, output);
// Invalid range starting index and ending index greater than object length but within Cipher Block size, returns empty object
objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("bytes=216-217")
.key(objectKey));
output = objectResponse.asUtf8String();
assertEquals("", output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void AesGcmV3toV3FailsRangeExceededObjectLength() {
final String objectKey = appendTestSuffix("aes-gcm-v3-to-v3-ranged-get-out-of-range");
final String input = "0bcdefghijklmnopqrst0BCDEFGHIJKLMNOPQRST" +
"1bcdefghijklmnopqrst1BCDEFGHIJKLMNOPQRST" +
"2bcdefghijklmnopqrst2BCDEFGHIJKLMNOPQRST" +
"3bcdefghijklmnopqrst3BCDEFGHIJKLMNOPQRST" +
"4bcdefghijklmnopqrst4BCDEFGHIJKLMNOPQRST";
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.enableLegacyUnauthenticatedModes(true)
.build();
v3Client.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), RequestBody.fromString(input));
// Invalid range exceed object length, Throws S3EncryptionClientException wrapped with S3Exception
assertThrows(S3EncryptionClientException.class, () -> v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("bytes=300-400")
.key(objectKey)));
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void AsyncAesGcmV3toV3FailsRangeExceededObjectLength() {
final String objectKey = appendTestSuffix("aes-gcm-v3-to-v3-ranged-get-out-of-range");
final String input = "0bcdefghijklmnopqrst0BCDEFGHIJKLMNOPQRST" +
"1bcdefghijklmnopqrst1BCDEFGHIJKLMNOPQRST" +
"2bcdefghijklmnopqrst2BCDEFGHIJKLMNOPQRST" +
"3bcdefghijklmnopqrst3BCDEFGHIJKLMNOPQRST" +
"4bcdefghijklmnopqrst4BCDEFGHIJKLMNOPQRST";
// Async Client
S3AsyncClient asyncClient = S3AsyncEncryptionClient.builder()
.aesKey(AES_KEY)
.enableLegacyUnauthenticatedModes(true)
.build();
asyncClient.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.build(), AsyncRequestBody.fromString(input)).join();
try {
// Invalid range exceed object length, Throws S3Exception nested inside CompletionException
asyncClient.getObject(builder -> builder
.bucket(BUCKET)
.range("bytes=300-400")
.key(objectKey), AsyncResponseTransformer.toBytes()).join();
} catch (CompletionException e) {
assertEquals(S3Exception.class, e.getCause().getClass());
}
// Cleanup
deleteObject(BUCKET, objectKey, asyncClient);
asyncClient.close();
}
@Test
public void AesCbcV1toV3RangedGet() {
final String objectKey = appendTestSuffix("aes-cbc-v1-to-v3-ranged-get");
// V1 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
CryptoConfiguration v1CryptoConfig =
new CryptoConfiguration();
AmazonS3Encryption v1Client = AmazonS3EncryptionClient.encryptionBuilder()
.withCryptoConfiguration(v1CryptoConfig)
.withEncryptionMaterials(materialsProvider)
.build();
// This string is 200 characters/bytes long
// Due to padding, its ciphertext will be 208 bytes
final String input = "0bcdefghijklmnopqrst0BCDEFGHIJKLMNOPQRST" +
"1bcdefghijklmnopqrst1BCDEFGHIJKLMNOPQRST" +
"2bcdefghijklmnopqrst2BCDEFGHIJKLMNOPQRST" +
"3bcdefghijklmnopqrst3BCDEFGHIJKLMNOPQRST" +
"4bcdefghijklmnopqrst4BCDEFGHIJKLMNOPQRST";
v1Client.putObject(BUCKET, objectKey, input);
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.enableLegacyWrappingAlgorithms(true)
.enableLegacyUnauthenticatedModes(true)
.build();
// Valid Range
ResponseBytes<GetObjectResponse> objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("bytes=10-20")
.key(objectKey));
String output = objectResponse.asUtf8String();
assertEquals("klmnopqrst0", output);
// Valid start index within input and end index out of range, returns object from start index to End of Stream
objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("bytes=190-300")
.key(objectKey));
output = objectResponse.asUtf8String();
assertEquals("KLMNOPQRST", output);
// Invalid range start index range greater than ending index, returns entire object
objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("bytes=100-50")
.key(objectKey));
output = objectResponse.asUtf8String();
assertEquals(input, output);
// Invalid range format, returns entire object
objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("10-20")
.key(objectKey));
output = objectResponse.asUtf8String();
assertEquals(input, output);
// Invalid range starting index and ending index greater than object length
// but within Cipher Block size, returns empty object
objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("bytes=216-217")
.key(objectKey));
output = objectResponse.asUtf8String();
assertEquals("", output);
// Invalid range starting index and ending index greater than object length
// but within Cipher Block size, returns empty object
objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("bytes=216-218")
.key(objectKey));
output = objectResponse.asUtf8String();
assertEquals("", output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void AesCbcV1toV3FailsRangeExceededObjectLength() {
final String objectKey = appendTestSuffix("aes-cbc-v1-to-v3-ranged-get-out-of-range");
// V1 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
CryptoConfiguration v1CryptoConfig =
new CryptoConfiguration();
AmazonS3Encryption v1Client = AmazonS3EncryptionClient.encryptionBuilder()
.withCryptoConfiguration(v1CryptoConfig)
.withEncryptionMaterials(materialsProvider)
.build();
final String input = "0bcdefghijklmnopqrst0BCDEFGHIJKLMNOPQRST" +
"1bcdefghijklmnopqrst1BCDEFGHIJKLMNOPQRST" +
"2bcdefghijklmnopqrst2BCDEFGHIJKLMNOPQRST" +
"3bcdefghijklmnopqrst3BCDEFGHIJKLMNOPQRST" +
"4bcdefghijklmnopqrst4BCDEFGHIJKLMNOPQRST";
v1Client.putObject(BUCKET, objectKey, input);
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.enableLegacyWrappingAlgorithms(true)
.enableLegacyUnauthenticatedModes(true)
.build();
// Invalid range exceed object length, Throws S3EncryptionClientException wrapped with S3Exception
assertThrows(S3EncryptionClientException.class, () -> v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.range("bytes=300-400")
.key(objectKey)));
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
}
| 2,212 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/S3AsyncEncryptionClientTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3;
import com.amazonaws.services.s3.AmazonS3Encryption;
import com.amazonaws.services.s3.AmazonS3EncryptionClient;
import com.amazonaws.services.s3.AmazonS3EncryptionClientV2;
import com.amazonaws.services.s3.AmazonS3EncryptionV2;
import com.amazonaws.services.s3.model.CryptoConfiguration;
import com.amazonaws.services.s3.model.CryptoConfigurationV2;
import com.amazonaws.services.s3.model.CryptoMode;
import com.amazonaws.services.s3.model.CryptoStorageMode;
import com.amazonaws.services.s3.model.EncryptionMaterials;
import com.amazonaws.services.s3.model.EncryptionMaterialsProvider;
import com.amazonaws.services.s3.model.StaticEncryptionMaterialsProvider;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.CopyObjectResponse;
import software.amazon.awssdk.services.s3.model.DeleteObjectResponse;
import software.amazon.awssdk.services.s3.model.DeleteObjectsResponse;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.ObjectIdentifier;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.BUCKET;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.appendTestSuffix;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.deleteObject;
public class S3AsyncEncryptionClientTest {
private static SecretKey AES_KEY;
@BeforeAll
public static void setUp() throws NoSuchAlgorithmException {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
AES_KEY = keyGen.generateKey();
}
@Test
public void putAsyncGetDefault() {
final String objectKey = appendTestSuffix("put-async-get-default");
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
S3AsyncClient v3AsyncClient = S3AsyncEncryptionClient.builder()
.aesKey(AES_KEY)
.build();
final String input = "PutAsyncGetDefault";
CompletableFuture<PutObjectResponse> futurePut = v3AsyncClient.putObject(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.build(), AsyncRequestBody.fromString(input));
// Block on completion of the futurePut
futurePut.join();
ResponseBytes<GetObjectResponse> getResponse = v3Client.getObject(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.build(), ResponseTransformer.toBytes());
assertEquals(input, getResponse.asUtf8String());
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
v3AsyncClient.close();
}
@Test
public void putDefaultGetAsync() {
final String objectKey = appendTestSuffix("put-default-get-async");
S3Client v3Client = S3EncryptionClient.builder()
.aesKey(AES_KEY)
.build();
S3AsyncClient v3AsyncClient = S3AsyncEncryptionClient.builder()
.aesKey(AES_KEY)
.build();
final String input = "PutDefaultGetAsync";
v3Client.putObject(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.build(), RequestBody.fromString(input));
CompletableFuture<ResponseBytes<GetObjectResponse>> futureGet = v3AsyncClient.getObject(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.build(), AsyncResponseTransformer.toBytes());
// Just wait for the future to complete
ResponseBytes<GetObjectResponse> getResponse = futureGet.join();
assertEquals(input, getResponse.asUtf8String());
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
v3AsyncClient.close();
}
@Test
public void putAsyncGetAsync() {
final String objectKey = appendTestSuffix("put-async-get-async");
S3AsyncClient v3AsyncClient = S3AsyncEncryptionClient.builder()
.aesKey(AES_KEY)
.build();
final String input = "PutAsyncGetAsync";
CompletableFuture<PutObjectResponse> futurePut = v3AsyncClient.putObject(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.build(), AsyncRequestBody.fromString(input));
// Block on completion of the futurePut
futurePut.join();
CompletableFuture<ResponseBytes<GetObjectResponse>> futureGet = v3AsyncClient.getObject(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.build(), AsyncResponseTransformer.toBytes());
// Just wait for the future to complete
ResponseBytes<GetObjectResponse> getResponse = futureGet.join();
assertEquals(input, getResponse.asUtf8String());
// Cleanup
deleteObject(BUCKET, objectKey, v3AsyncClient);
v3AsyncClient.close();
}
@Test
public void aesCbcV1toV3Async() {
final String objectKey = appendTestSuffix("aes-cbc-v1-to-v3-async");
// V1 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
CryptoConfiguration v1CryptoConfig =
new CryptoConfiguration();
AmazonS3Encryption v1Client = AmazonS3EncryptionClient.encryptionBuilder()
.withCryptoConfiguration(v1CryptoConfig)
.withEncryptionMaterials(materialsProvider)
.build();
final String input = "0bcdefghijklmnopqrst0BCDEFGHIJKLMNOPQRST";
v1Client.putObject(BUCKET, objectKey, input);
// V3 Client
S3AsyncClient v3Client = S3AsyncEncryptionClient.builder()
.aesKey(AES_KEY)
.enableLegacyWrappingAlgorithms(true)
.enableLegacyUnauthenticatedModes(true)
.build();
CompletableFuture<ResponseBytes<GetObjectResponse>> futureResponse = v3Client.getObject(builder -> builder
.bucket(BUCKET)
.key(objectKey), AsyncResponseTransformer.toBytes());
ResponseBytes<GetObjectResponse> response = futureResponse.join();
String output = response.asUtf8String();
assertEquals(input, output);
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void failAesCbcV1toV3AsyncWhenDisabled() {
final String objectKey = appendTestSuffix("fail-aes-cbc-v1-to-v3-async-when-disabled");
// V1 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
CryptoConfiguration v1CryptoConfig =
new CryptoConfiguration();
AmazonS3Encryption v1Client = AmazonS3EncryptionClient.encryptionBuilder()
.withCryptoConfiguration(v1CryptoConfig)
.withEncryptionMaterials(materialsProvider)
.build();
final String input = "0bcdefghijklmnopqrst0BCDEFGHIJKLMNOPQRST";
v1Client.putObject(BUCKET, objectKey, input);
// V3 Client
S3AsyncClient v3Client = S3AsyncEncryptionClient.builder()
.aesKey(AES_KEY)
.enableLegacyWrappingAlgorithms(true)
.build();
try {
CompletableFuture<ResponseBytes<GetObjectResponse>> futureResponse = v3Client.getObject(builder -> builder
.bucket(BUCKET)
.key(objectKey), AsyncResponseTransformer.toBytes());
futureResponse.join();
} catch (CompletionException e) {
assertEquals(S3EncryptionClientException.class, e.getCause().getClass());
}
// Cleanup
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void AsyncAesGcmV2toV3WithInstructionFile() {
final String objectKey = appendTestSuffix("async-aes-gcm-v2-to-v3-with-instruction-file");
// V2 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
CryptoConfigurationV2 cryptoConfig =
new CryptoConfigurationV2(CryptoMode.StrictAuthenticatedEncryption)
.withStorageMode(CryptoStorageMode.InstructionFile);
AmazonS3EncryptionV2 v2Client = AmazonS3EncryptionClientV2.encryptionBuilder()
.withCryptoConfiguration(cryptoConfig)
.withEncryptionMaterialsProvider(materialsProvider)
.build();
// V3 Async Client
S3AsyncClient v3AsyncClient = S3AsyncEncryptionClient.builder()
.aesKey(AES_KEY)
.build();
// Asserts
final String input = "AesGcmV2toV3";
v2Client.putObject(BUCKET, objectKey, input);
CompletableFuture<ResponseBytes<GetObjectResponse>> futureGet = v3AsyncClient.getObject(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.build(), AsyncResponseTransformer.toBytes());
String outputAsync = futureGet.join().asUtf8String();
assertEquals(input, outputAsync);
// Cleanup
deleteObject(BUCKET, objectKey, v3AsyncClient);
v3AsyncClient.close();
}
@Test
public void deleteObjectWithInstructionFileSuccessAsync() {
final String objectKey = appendTestSuffix("async-delete-object-with-instruction-file");
// V2 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
CryptoConfigurationV2 cryptoConfig =
new CryptoConfigurationV2(CryptoMode.StrictAuthenticatedEncryption)
.withStorageMode(CryptoStorageMode.InstructionFile);
AmazonS3EncryptionV2 v2Client = AmazonS3EncryptionClientV2.encryptionBuilder()
.withCryptoConfiguration(cryptoConfig)
.withEncryptionMaterialsProvider(materialsProvider)
.build();
// V3 Client
S3AsyncClient v3Client = S3AsyncEncryptionClient.builder()
.aesKey(AES_KEY)
.build();
final String input = "DeleteObjectWithInstructionFileSuccess";
v2Client.putObject(BUCKET, objectKey, input);
// Delete Object
CompletableFuture<DeleteObjectResponse> response = v3Client.deleteObject(builder -> builder
.bucket(BUCKET)
.key(objectKey));
// Ensure completion
response.join();
S3Client s3Client = S3Client.builder().build();
// Assert throw NoSuchKeyException when getObject for objectKey
assertThrows(S3Exception.class, () -> s3Client.getObject(builder -> builder
.bucket(BUCKET)
.key(objectKey)));
assertThrows(S3Exception.class, () -> s3Client.getObject(builder -> builder
.bucket(BUCKET)
.key(objectKey + ".instruction")));
// Cleanup
v3Client.close();
s3Client.close();
}
@Test
public void deleteObjectsWithInstructionFilesSuccessAsync() {
final String[] objectKeys = {appendTestSuffix("async-delete-object-with-instruction-file-1"),
appendTestSuffix("async-delete-object-with-instruction-file-2"),
appendTestSuffix("async-delete-object-with-instruction-file-3")};
// V2 Client
EncryptionMaterialsProvider materialsProvider =
new StaticEncryptionMaterialsProvider(new EncryptionMaterials(AES_KEY));
CryptoConfigurationV2 cryptoConfig =
new CryptoConfigurationV2(CryptoMode.StrictAuthenticatedEncryption)
.withStorageMode(CryptoStorageMode.InstructionFile);
AmazonS3EncryptionV2 v2Client = AmazonS3EncryptionClientV2.encryptionBuilder()
.withCryptoConfiguration(cryptoConfig)
.withEncryptionMaterialsProvider(materialsProvider)
.build();
// V3 Client
S3AsyncClient v3Client = S3AsyncEncryptionClient.builder()
.aesKey(AES_KEY)
.build();
final String input = "DeleteObjectsWithInstructionFileSuccess";
List<ObjectIdentifier> objects = new ArrayList<>();
for (String objectKey : objectKeys) {
v2Client.putObject(BUCKET, objectKey, input);
objects.add(ObjectIdentifier.builder().key(objectKey).build());
}
// Delete Objects from S3 Buckets
CompletableFuture<DeleteObjectsResponse> response = v3Client.deleteObjects(builder -> builder
.bucket(BUCKET)
.delete(builder1 -> builder1.objects(objects)));
// Block on completion
response.join();
S3Client s3Client = S3Client.builder().build();
// Assert throw NoSuchKeyException when getObject for any of objectKeys
assertThrows(S3Exception.class, () -> s3Client.getObject(builder -> builder
.bucket(BUCKET)
.key(objectKeys[0])));
assertThrows(S3Exception.class, () -> s3Client.getObject(builder -> builder
.bucket(BUCKET)
.key(objectKeys[0] + ".instruction")));
// Cleanup
v3Client.close();
s3Client.close();
}
@Test
public void deleteObjectWithWrongObjectKeySuccessAsync() {
// V3 Client
S3AsyncClient v3Client = S3AsyncEncryptionClient.builder()
.aesKey(AES_KEY)
.build();
assertDoesNotThrow(() -> v3Client.deleteObject(builder -> builder.bucket(BUCKET).key("InvalidKey")));
// Cleanup
v3Client.close();
}
@Test
public void copyObjectTransparentlyAsync() {
final String objectKey = appendTestSuffix("copy-object-from-here-async");
final String newObjectKey = appendTestSuffix("copy-object-to-here-async");
S3AsyncClient v3AsyncClient = S3AsyncEncryptionClient.builder()
.aesKey(AES_KEY)
.build();
final String input = "CopyObjectAsync";
CompletableFuture<PutObjectResponse> futurePut = v3AsyncClient.putObject(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.build(), AsyncRequestBody.fromString(input));
// Block on completion of the futurePut
futurePut.join();
CompletableFuture<CopyObjectResponse> futureCopy = v3AsyncClient.copyObject(builder -> builder
.sourceBucket(BUCKET)
.destinationBucket(BUCKET)
.sourceKey(objectKey)
.destinationKey(newObjectKey)
.build());
// Block on copy future
futureCopy.join();
// Decrypt new object
CompletableFuture<ResponseBytes<GetObjectResponse>> futureGet = v3AsyncClient.getObject(builder -> builder
.bucket(BUCKET)
.key(newObjectKey)
.build(), AsyncResponseTransformer.toBytes());
ResponseBytes<GetObjectResponse> getResponse = futureGet.join();
assertEquals(input, getResponse.asUtf8String());
// Cleanup
deleteObject(BUCKET, objectKey, v3AsyncClient);
deleteObject(BUCKET, newObjectKey, v3AsyncClient);
v3AsyncClient.close();
}
}
| 2,213 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/S3EncryptionClientMultipartUploadTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3;
import org.apache.commons.io.IOUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.CompletedPart;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.services.s3.model.SdkPartType;
import software.amazon.awssdk.services.s3.model.UploadPartRequest;
import software.amazon.awssdk.services.s3.model.UploadPartResponse;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.encryption.s3.utils.BoundedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static software.amazon.encryption.s3.S3EncryptionClient.withAdditionalConfiguration;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.BUCKET;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.KMS_KEY_ID;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.appendTestSuffix;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.deleteObject;
public class S3EncryptionClientMultipartUploadTest {
private static Provider PROVIDER;
@BeforeAll
public static void setUp() throws NoSuchAlgorithmException {
Security.addProvider(new BouncyCastleProvider());
PROVIDER = Security.getProvider("BC");
}
@Test
public void multipartPutObjectAsync() throws IOException {
final String objectKey = appendTestSuffix("multipart-put-object-async");
final long fileSizeLimit = 1024 * 1024 * 100;
final InputStream inputStream = new BoundedInputStream(fileSizeLimit);
final InputStream objectStreamForResult = new BoundedInputStream(fileSizeLimit);
S3AsyncClient v3Client = S3AsyncEncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.enableMultipartPutObject(true)
.enableDelayedAuthenticationMode(true)
.cryptoProvider(PROVIDER)
.build();
Map<String, String> encryptionContext = new HashMap<>();
encryptionContext.put("user-metadata-key", "user-metadata-value-v3-to-v3");
CompletableFuture<PutObjectResponse> futurePut = v3Client.putObject(builder -> builder
.bucket(BUCKET)
.overrideConfiguration(withAdditionalConfiguration(encryptionContext))
.key(objectKey), AsyncRequestBody.fromInputStream(inputStream, fileSizeLimit, Executors.newSingleThreadExecutor()));
futurePut.join();
// Asserts
CompletableFuture<ResponseInputStream<GetObjectResponse>> getFuture = v3Client.getObject(builder -> builder
.bucket(BUCKET)
.overrideConfiguration(S3EncryptionClient.withAdditionalConfiguration(encryptionContext))
.key(objectKey), AsyncResponseTransformer.toBlockingInputStream());
ResponseInputStream<GetObjectResponse> output = getFuture.join();
assertTrue(IOUtils.contentEquals(objectStreamForResult, output));
deleteObject(BUCKET, objectKey, v3Client);
v3Client.close();
}
@Test
public void multipartPutObjectAsyncLargeObjectFails() {
final String objectKey = appendTestSuffix("multipart-put-object-async-large-object-fails");
// Tight bound on the max GCM limit
final long fileSizeLimit = ((1L << 39) - 256 / 8) + 1;
final InputStream inputStream = new BoundedInputStream(fileSizeLimit);
S3AsyncClient v3Client = S3AsyncEncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.enableMultipartPutObject(true)
.enableDelayedAuthenticationMode(true)
.cryptoProvider(PROVIDER)
.build();
Map<String, String> encryptionContext = new HashMap<>();
encryptionContext.put("user-metadata-key", "user-metadata-value-v3-to-v3");
assertThrows(S3EncryptionClientException.class, () -> v3Client.putObject(builder -> builder
.bucket(BUCKET)
.overrideConfiguration(withAdditionalConfiguration(encryptionContext))
.key(objectKey), AsyncRequestBody.fromInputStream(inputStream, fileSizeLimit, Executors.newSingleThreadExecutor())));
v3Client.close();
}
@Test
public void multipartPutObject() throws IOException {
final String objectKey = appendTestSuffix("multipart-put-object");
final long fileSizeLimit = 1024 * 1024 * 100;
final InputStream inputStream = new BoundedInputStream(fileSizeLimit);
final InputStream objectStreamForResult = new BoundedInputStream(fileSizeLimit);
S3Client v3Client = S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.enableMultipartPutObject(true)
.enableDelayedAuthenticationMode(true)
.cryptoProvider(PROVIDER)
.build();
Map<String, String> encryptionContext = new HashMap<>();
encryptionContext.put("user-metadata-key", "user-metadata-value-v3-to-v3");
v3Client.putObject(builder -> builder
.bucket(BUCKET)
.overrideConfiguration(withAdditionalConfiguration(encryptionContext))
.key(objectKey), RequestBody.fromInputStream(inputStream, fileSizeLimit));
// Asserts
ResponseInputStream<GetObjectResponse> output = v3Client.getObject(builder -> builder
.bucket(BUCKET)
.overrideConfiguration(S3EncryptionClient.withAdditionalConfiguration(encryptionContext))
.key(objectKey));
assertTrue(IOUtils.contentEquals(objectStreamForResult, output));
v3Client.deleteObject(builder -> builder.bucket(BUCKET).key(objectKey));
v3Client.close();
}
/*
This test ensures that an object larger than the max safe GCM limit
cannot be uploaded using the low-level multipart upload API.
It is currently disabled as it alone takes 10x the duration of the
entire rest of the test suite. In the future, it would be best to
have a "long" test suite containing this test and any other tests
which take more than 5-10 minutes to complete.
*/
// @Test
// public void multipartUploadV3OutputStreamLargeObjectFails() throws IOException {
// final String objectKey = appendTestSuffix("multipart-upload-v3-output-stream-fails");
//
// // Overall "file" is ~68GB, split into 10MB parts
// // Tight bound on the max GCM limit
// final long fileSizeLimit = ((1L << 39) - 256 / 8) + 1;
// final int PART_SIZE = 10 * 1024 * 1024;
// final InputStream inputStream = new BoundedInputStream(fileSizeLimit);
//
// // V3 Client
// S3Client v3Client = S3EncryptionClient.builder()
// .kmsKeyId(KMS_KEY_ID)
// .enableDelayedAuthenticationMode(true)
// .cryptoProvider(PROVIDER)
// .build();
//
// // Create Multipart upload request to S3
// CreateMultipartUploadResponse initiateResult = v3Client.createMultipartUpload(builder ->
// builder.bucket(BUCKET).key(objectKey));
//
// List<CompletedPart> partETags = new ArrayList<>();
//
// int bytesRead, bytesSent = 0;
// // 10MB parts
// byte[] partData = new byte[PART_SIZE];
// ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// int partsSent = 1;
//
// while ((bytesRead = inputStream.read(partData, 0, partData.length)) != -1) {
// outputStream.write(partData, 0, bytesRead);
// if (bytesSent < PART_SIZE) {
// bytesSent += bytesRead;
// continue;
// }
//
// UploadPartRequest uploadPartRequest = UploadPartRequest.builder()
// .bucket(BUCKET)
// .key(objectKey)
// .uploadId(initiateResult.uploadId())
// .partNumber(partsSent)
// .build();
//
// final InputStream partInputStream = new ByteArrayInputStream(outputStream.toByteArray());
// UploadPartResponse uploadPartResult = v3Client.uploadPart(uploadPartRequest,
// RequestBody.fromInputStream(partInputStream, partInputStream.available()));
// partETags.add(CompletedPart.builder()
// .partNumber(partsSent)
// .eTag(uploadPartResult.eTag())
// .build());
// outputStream.reset();
// bytesSent = 0;
// partsSent++;
// }
// inputStream.close();
//
// // Last Part
// UploadPartRequest uploadPartRequest = UploadPartRequest.builder()
// .bucket(BUCKET)
// .key(objectKey)
// .uploadId(initiateResult.uploadId())
// .partNumber(partsSent)
// .sdkPartType(SdkPartType.LAST)
// .build();
//
// final InputStream partInputStream = new ByteArrayInputStream(outputStream.toByteArray());
// UploadPartResponse uploadPartResult = v3Client.uploadPart(uploadPartRequest,
// RequestBody.fromInputStream(partInputStream, partInputStream.available()));
// partETags.add(CompletedPart.builder()
// .partNumber(partsSent)
// .eTag(uploadPartResult.eTag())
// .build());
//
// // Complete the multipart upload.
// v3Client.completeMultipartUpload(builder -> builder
// .bucket(BUCKET)
// .key(objectKey)
// .uploadId(initiateResult.uploadId())
// .multipartUpload(partBuilder -> partBuilder.parts(partETags)));
//
// // Asserts
// InputStream resultStream = v3Client.getObjectAsBytes(builder -> builder
// .bucket(BUCKET)
// .key(objectKey)).asInputStream();
//
// assertTrue(IOUtils.contentEquals(new BoundedInputStream(fileSizeLimit), resultStream));
// resultStream.close();
//
// v3Client.deleteObject(builder -> builder.bucket(BUCKET).key(objectKey));
// v3Client.close();
// }
@Test
public void multipartPutObjectLargeObjectFails() {
final String objectKey = appendTestSuffix("multipart-put-object-large-fails");
// Tight bound on the max GCM limit
final long fileSizeLimit = ((1L << 39) - 256 / 8) + 1;
final InputStream inputStream = new BoundedInputStream(fileSizeLimit);
S3Client v3Client = S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.enableMultipartPutObject(true)
.enableDelayedAuthenticationMode(true)
.cryptoProvider(PROVIDER)
.build();
Map<String, String> encryptionContext = new HashMap<>();
encryptionContext.put("user-metadata-key", "user-metadata-value-v3-to-v3");
assertThrows(S3EncryptionClientException.class, () -> v3Client.putObject(builder -> builder
.bucket(BUCKET)
.overrideConfiguration(withAdditionalConfiguration(encryptionContext))
.key(objectKey), RequestBody.fromInputStream(inputStream, fileSizeLimit)));
v3Client.close();
}
@Test
public void multipartUploadV3OutputStream() throws IOException {
final String objectKey = appendTestSuffix("multipart-upload-v3-output-stream");
// Overall "file" is 100MB, split into 10MB parts
final long fileSizeLimit = 1024 * 1024 * 100;
final int PART_SIZE = 10 * 1024 * 1024;
final InputStream inputStream = new BoundedInputStream(fileSizeLimit);
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.enableDelayedAuthenticationMode(true)
.cryptoProvider(PROVIDER)
.build();
// Create Multipart upload request to S3
CreateMultipartUploadResponse initiateResult = v3Client.createMultipartUpload(builder ->
builder.bucket(BUCKET).key(objectKey));
List<CompletedPart> partETags = new ArrayList<>();
int bytesRead, bytesSent = 0;
// 10MB parts
byte[] partData = new byte[PART_SIZE];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int partsSent = 1;
while ((bytesRead = inputStream.read(partData, 0, partData.length)) != -1) {
outputStream.write(partData, 0, bytesRead);
if (bytesSent < PART_SIZE) {
bytesSent += bytesRead;
continue;
}
UploadPartRequest uploadPartRequest = UploadPartRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.uploadId(initiateResult.uploadId())
.partNumber(partsSent)
.build();
final InputStream partInputStream = new ByteArrayInputStream(outputStream.toByteArray());
UploadPartResponse uploadPartResult = v3Client.uploadPart(uploadPartRequest,
RequestBody.fromInputStream(partInputStream, partInputStream.available()));
partETags.add(CompletedPart.builder()
.partNumber(partsSent)
.eTag(uploadPartResult.eTag())
.build());
outputStream.reset();
bytesSent = 0;
partsSent++;
}
inputStream.close();
// Last Part
UploadPartRequest uploadPartRequest = UploadPartRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.uploadId(initiateResult.uploadId())
.partNumber(partsSent)
.sdkPartType(SdkPartType.LAST)
.build();
final InputStream partInputStream = new ByteArrayInputStream(outputStream.toByteArray());
UploadPartResponse uploadPartResult = v3Client.uploadPart(uploadPartRequest,
RequestBody.fromInputStream(partInputStream, partInputStream.available()));
partETags.add(CompletedPart.builder()
.partNumber(partsSent)
.eTag(uploadPartResult.eTag())
.build());
// Complete the multipart upload.
v3Client.completeMultipartUpload(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.uploadId(initiateResult.uploadId())
.multipartUpload(partBuilder -> partBuilder.parts(partETags)));
// Asserts
InputStream resultStream = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey)).asInputStream();
assertTrue(IOUtils.contentEquals(new BoundedInputStream(fileSizeLimit), resultStream));
resultStream.close();
v3Client.deleteObject(builder -> builder.bucket(BUCKET).key(objectKey));
v3Client.close();
}
@Test
public void multipartUploadV3OutputStreamPartSize() throws IOException {
final String objectKey = appendTestSuffix("multipart-upload-v3-output-stream-part-size");
// Overall "file" is 30MB, split into 10MB parts
final long fileSizeLimit = 1024 * 1024 * 30;
final int PART_SIZE = 10 * 1024 * 1024;
final InputStream inputStream = new BoundedInputStream(fileSizeLimit);
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.enableDelayedAuthenticationMode(true)
.cryptoProvider(PROVIDER)
.build();
// Create Multipart upload request to S3
CreateMultipartUploadResponse initiateResult = v3Client.createMultipartUpload(builder ->
builder.bucket(BUCKET).key(objectKey));
List<CompletedPart> partETags = new ArrayList<>();
int bytesRead, bytesSent = 0;
// 10MB parts
byte[] partData = new byte[PART_SIZE];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int partsSent = 1;
while ((bytesRead = inputStream.read(partData, 0, partData.length)) != -1) {
outputStream.write(partData, 0, bytesRead);
if (bytesSent < PART_SIZE) {
bytesSent += bytesRead;
continue;
}
final InputStream partInputStream = new ByteArrayInputStream(outputStream.toByteArray());
UploadPartRequest uploadPartRequest = UploadPartRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.uploadId(initiateResult.uploadId())
.partNumber(partsSent)
.contentLength((long) partInputStream.available())
.build();
UploadPartResponse uploadPartResult = v3Client.uploadPart(uploadPartRequest,
RequestBody.fromInputStream(partInputStream, partInputStream.available()));
partETags.add(CompletedPart.builder()
.partNumber(partsSent)
.eTag(uploadPartResult.eTag())
.build());
outputStream.reset();
bytesSent = 0;
partsSent++;
}
final InputStream partInputStream = new ByteArrayInputStream(outputStream.toByteArray());
// Last Part
UploadPartRequest uploadPartRequest = UploadPartRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.uploadId(initiateResult.uploadId())
.partNumber(partsSent)
.contentLength((long) partInputStream.available())
.sdkPartType(SdkPartType.LAST)
.build();
UploadPartResponse uploadPartResult = v3Client.uploadPart(uploadPartRequest,
RequestBody.fromInputStream(partInputStream, partInputStream.available()));
partETags.add(CompletedPart.builder()
.partNumber(partsSent)
.eTag(uploadPartResult.eTag())
.build());
// Complete the multipart upload.
v3Client.completeMultipartUpload(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.uploadId(initiateResult.uploadId())
.multipartUpload(partBuilder -> partBuilder.parts(partETags)));
// Asserts
ResponseBytes<GetObjectResponse> result = v3Client.getObjectAsBytes(builder -> builder
.bucket(BUCKET)
.key(objectKey));
String inputAsString = IoUtils.toUtf8String(new BoundedInputStream(fileSizeLimit));
String outputAsString = IoUtils.toUtf8String(result.asInputStream());
assertEquals(inputAsString, outputAsString);
v3Client.deleteObject(builder -> builder.bucket(BUCKET).key(objectKey));
v3Client.close();
}
@Test
public void multipartUploadV3OutputStreamPartSizeMismatch() throws IOException {
final String objectKey = appendTestSuffix("multipart-upload-v3-output-stream-part-size-mismatch");
// Overall "file" is 30MB, split into 10MB parts
final long fileSizeLimit = 1024 * 1024 * 30;
final int PART_SIZE = 10 * 1024 * 1024;
final InputStream inputStream = new BoundedInputStream(fileSizeLimit);
// V3 Client
S3Client v3Client = S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.enableDelayedAuthenticationMode(true)
.cryptoProvider(PROVIDER)
.build();
// Create Multipart upload request to S3
CreateMultipartUploadResponse initiateResult = v3Client.createMultipartUpload(builder ->
builder.bucket(BUCKET).key(objectKey));
int bytesRead, bytesSent = 0;
// 10MB parts
byte[] partData = new byte[PART_SIZE];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int partsSent = 1;
while ((bytesRead = inputStream.read(partData, 0, partData.length)) != -1) {
outputStream.write(partData, 0, bytesRead);
if (bytesSent < PART_SIZE) {
bytesSent += bytesRead;
continue;
}
final InputStream partInputStream = new ByteArrayInputStream(outputStream.toByteArray());
UploadPartRequest uploadPartRequest = UploadPartRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.uploadId(initiateResult.uploadId())
.partNumber(partsSent)
.contentLength((long) partInputStream.available() + 1) // mismatch
.build();
assertThrows(S3EncryptionClientException.class, () -> v3Client.uploadPart(uploadPartRequest,
RequestBody.fromInputStream(partInputStream, partInputStream.available())));
}
v3Client.deleteObject(builder -> builder.bucket(BUCKET).key(objectKey));
v3Client.close();
}
}
| 2,214 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/materials/DefaultDataKeyGeneratorTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.jupiter.api.Test;
import software.amazon.encryption.s3.algorithms.AlgorithmSuite;
import javax.crypto.SecretKey;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DefaultDataKeyGeneratorTest {
private final DataKeyGenerator dataKeyGenerator = new DefaultDataKeyGenerator();
@Test
public void testGenerateDataKey() {
SecretKey actualSecretKey = dataKeyGenerator.generateDataKey(AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF, null);
assertEquals("AES", actualSecretKey.getAlgorithm());
actualSecretKey = dataKeyGenerator.generateDataKey(AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF, new BouncyCastleProvider());
assertEquals("AES", actualSecretKey.getAlgorithm());
}
} | 2,215 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/materials/DecryptionMaterialsTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.encryption.s3.algorithms.AlgorithmSuite;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
public class DecryptionMaterialsTest {
private DecryptionMaterials actualDecryptionMaterials;
private GetObjectRequest s3Request;
private Map<String, String> encryptionContext = new HashMap<>();
@BeforeEach
public void setUp() {
s3Request = GetObjectRequest.builder().bucket("testBucket").key("testKey").build();
encryptionContext.put("testKey", "testValue");
actualDecryptionMaterials = DecryptionMaterials.builder()
.algorithmSuite(AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF)
.s3Request(s3Request)
.encryptionContext(encryptionContext)
.build();
}
@Test
public void testS3Request() {
assertEquals(s3Request, actualDecryptionMaterials.s3Request());
}
@Test
public void testAlgorithmSuite() {
assertEquals(AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF, actualDecryptionMaterials.algorithmSuite());
assertNotEquals(AlgorithmSuite.ALG_AES_256_CBC_IV16_NO_KDF, actualDecryptionMaterials.algorithmSuite());
}
@Test
public void testEncryptionContext() {
assertEquals(encryptionContext, actualDecryptionMaterials.encryptionContext());
}
}
| 2,216 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/materials/EncryptionMaterialsRequestTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class EncryptionMaterialsRequestTest {
private PutObjectRequest request;
private EncryptionMaterialsRequest actualRequestBuilder;
private Map<String, String> encryptionContext = new HashMap<>();
@BeforeEach
public void setUp() {
request = PutObjectRequest.builder().bucket("testBucket").key("testKey").build();
encryptionContext.put("Key","Value");
actualRequestBuilder = EncryptionMaterialsRequest.builder()
.s3Request(request).encryptionContext(encryptionContext).build();
}
@Test
public void testS3Request() {
assertEquals(request, actualRequestBuilder.s3Request());
}
@Test
public void testEncryptionContext() {
assertEquals(encryptionContext, actualRequestBuilder.encryptionContext());
}
} | 2,217 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/materials/PartialRsaKeyPairTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.encryption.s3.S3EncryptionClientException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import static org.junit.jupiter.api.Assertions.*;
public class PartialRsaKeyPairTest {
private static final String KEY_ALGORITHM = "RSA";
private static KeyPair RSA_KEY_PAIR;
@BeforeAll
public static void setUp() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGen = java.security.KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(2048);
RSA_KEY_PAIR = keyPairGen.generateKeyPair();
}
@Test
public void testGetPublicKey() {
PartialRsaKeyPair partialRsaKeyPair = new PartialRsaKeyPair(null, RSA_KEY_PAIR.getPublic());
assertEquals(RSA_KEY_PAIR.getPublic(), partialRsaKeyPair.getPublicKey());
assertThrows(S3EncryptionClientException.class, partialRsaKeyPair::getPrivateKey);
assertEquals(KEY_ALGORITHM, partialRsaKeyPair.getPublicKey().getAlgorithm());
}
@Test
public void testGetPrivateKey() {
PartialRsaKeyPair partialRsaKeyPair = new PartialRsaKeyPair(RSA_KEY_PAIR.getPrivate(), null);
assertEquals(RSA_KEY_PAIR.getPrivate(), partialRsaKeyPair.getPrivateKey());
assertThrows(S3EncryptionClientException.class, partialRsaKeyPair::getPublicKey);
assertEquals(KEY_ALGORITHM, partialRsaKeyPair.getPrivateKey().getAlgorithm());
}
@Test
public void testBothKeysNull() {
assertThrows(S3EncryptionClientException.class, () -> new PartialRsaKeyPair(null, null));
}
@Test
public void testBuilder() {
PartialRsaKeyPair expectedKeyPair = new PartialRsaKeyPair(RSA_KEY_PAIR);
PartialRsaKeyPair actualKeyPair = PartialRsaKeyPair.builder()
.publicKey(RSA_KEY_PAIR.getPublic())
.privateKey(RSA_KEY_PAIR.getPrivate())
.build();
assertEquals(expectedKeyPair, actualKeyPair);
}
@Test
public void testInequality() {
PartialRsaKeyPair firstKeyPair = new PartialRsaKeyPair(RSA_KEY_PAIR);
PartialRsaKeyPair onlyPublicKeyPair = new PartialRsaKeyPair(null, RSA_KEY_PAIR.getPublic());
PartialRsaKeyPair onlyPrivateKeyPair = new PartialRsaKeyPair(RSA_KEY_PAIR.getPrivate(), null);
assertNotEquals(null, firstKeyPair);
assertNotEquals(firstKeyPair, onlyPublicKeyPair);
assertNotEquals(firstKeyPair, onlyPrivateKeyPair);
assertNotEquals(onlyPrivateKeyPair, onlyPublicKeyPair);
}
@Test
public void testHashCodeSameKeyPair() {
PartialRsaKeyPair firstKeyPair = new PartialRsaKeyPair(RSA_KEY_PAIR);
PartialRsaKeyPair secondKeyPair = new PartialRsaKeyPair(RSA_KEY_PAIR);
assertEquals(firstKeyPair.hashCode(), secondKeyPair.hashCode());
}
@Test
public void testHashCodeDifferentKeyPair() {
PartialRsaKeyPair firstKeyPair = new PartialRsaKeyPair(RSA_KEY_PAIR);
PartialRsaKeyPair secondKeyPair = new PartialRsaKeyPair(null, RSA_KEY_PAIR.getPublic());
assertNotEquals(firstKeyPair.hashCode(), secondKeyPair.hashCode());
}
}
| 2,218 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/materials/RsaKeyringTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import org.junit.jupiter.api.Test;
import software.amazon.encryption.s3.S3EncryptionClientException;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class RsaKeyringTest {
@Test
public void buildAesKeyringWithNullSecureRandomFails() {
assertThrows(S3EncryptionClientException.class, () -> AesKeyring.builder().secureRandom(null));
}
@Test
public void buildAesKeyringWithNullDataKeyGeneratorFails() {
assertThrows(S3EncryptionClientException.class, () -> AesKeyring.builder().dataKeyGenerator(null));
}
}
| 2,219 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/materials/EncryptedDataKeyTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class EncryptedDataKeyTest {
private EncryptedDataKey actualEncryptedDataKey;
private byte[] encryptedDataKey;
private String keyProviderId;
private byte[] keyProviderInfo;
@BeforeEach
public void setUp() {
keyProviderId = "testKeyProviderId";
keyProviderInfo = new byte[]{20, 10, 30, 5};
encryptedDataKey = new byte[]{20, 10, 30, 5};
actualEncryptedDataKey = EncryptedDataKey.builder()
.keyProviderId(keyProviderId)
.keyProviderInfo(keyProviderInfo)
.encryptedDataKey(encryptedDataKey)
.build();
}
@Test
public void keyProviderId() {
assertEquals(keyProviderId, actualEncryptedDataKey.keyProviderId());
}
@Test
public void keyProviderInfo() {
assertEquals(Arrays.toString(keyProviderInfo), Arrays.toString(actualEncryptedDataKey.keyProviderInfo()));
}
@Test
public void ciphertext() {
assertEquals(Arrays.toString(encryptedDataKey), Arrays.toString(actualEncryptedDataKey.encryptedDatakey()));
}
} | 2,220 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/materials/KmsKeyringTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import org.junit.jupiter.api.Test;
import software.amazon.encryption.s3.S3EncryptionClientException;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class KmsKeyringTest {
@Test
public void buildAesKeyringWithNullSecureRandomFails() {
assertThrows(S3EncryptionClientException.class, () -> AesKeyring.builder().secureRandom(null));
}
@Test
public void buildAesKeyringWithNullDataKeyGeneratorFails() {
assertThrows(S3EncryptionClientException.class, () -> AesKeyring.builder().dataKeyGenerator(null));
}
}
| 2,221 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/materials/EncryptionMaterialsTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.encryption.s3.algorithms.AlgorithmSuite;
import java.util.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
class EncryptionMaterialsTest {
private List<EncryptedDataKey> encryptedDataKeys = new ArrayList();
private byte[] plaintextDataKey;
private PutObjectRequest s3Request;
private EncryptionMaterials actualEncryptionMaterials;
private Map<String, String> encryptionContext = new HashMap<>();
@BeforeEach
public void setUp() {
s3Request = PutObjectRequest.builder().bucket("testBucket").key("testKey").build();
encryptionContext.put("Key","Value");
encryptedDataKeys.add(EncryptedDataKey.builder().keyProviderId("testKeyProviderId").build());
plaintextDataKey = "Test String".getBytes();
actualEncryptionMaterials = EncryptionMaterials.builder()
.s3Request(s3Request)
.algorithmSuite(AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF)
.encryptionContext(encryptionContext)
.encryptedDataKeys(encryptedDataKeys)
.plaintextDataKey(plaintextDataKey)
.build();
}
@Test
void testS3Request() {
assertEquals(s3Request, actualEncryptionMaterials.s3Request());
}
@Test
void testAlgorithmSuite() {
assertEquals(AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF, actualEncryptionMaterials.algorithmSuite());
assertNotEquals(AlgorithmSuite.ALG_AES_256_CBC_IV16_NO_KDF, actualEncryptionMaterials.algorithmSuite());
}
@Test
void testEncryptionContext() {
assertEquals(encryptionContext, actualEncryptionMaterials.encryptionContext());
}
@Test
void testEncryptedDataKeys() {
assertEquals(encryptedDataKeys, actualEncryptionMaterials.encryptedDataKeys());
}
@Test
void testPlaintextDataKey() {
assertEquals(Arrays.toString(plaintextDataKey), Arrays.toString(actualEncryptionMaterials.plaintextDataKey()));
}
@Test
void testToBuilder() {
EncryptionMaterials actualToBuilder = actualEncryptionMaterials.toBuilder().build();
assertEquals(s3Request, actualToBuilder.s3Request());
assertEquals(AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF, actualToBuilder.algorithmSuite());
assertEquals(encryptionContext, actualToBuilder.encryptionContext());
assertEquals(encryptedDataKeys, actualToBuilder.encryptedDataKeys());
assertEquals(Arrays.toString(plaintextDataKey), Arrays.toString(actualToBuilder.plaintextDataKey()));
}
} | 2,222 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/materials/AesKeyringTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import org.junit.jupiter.api.Test;
import software.amazon.encryption.s3.S3EncryptionClientException;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class AesKeyringTest {
@Test
public void testAesKeyringWithNullWrappingKeyFails() {
assertThrows(S3EncryptionClientException.class, () -> AesKeyring.builder().wrappingKey(null));
}
@Test
public void buildAesKeyringWithNullSecureRandomFails() {
assertThrows(S3EncryptionClientException.class, () -> AesKeyring.builder().secureRandom(null));
}
@Test
public void buildAesKeyringWithNullDataKeyGeneratorFails() {
assertThrows(S3EncryptionClientException.class, () -> AesKeyring.builder().dataKeyGenerator(null));
}
}
| 2,223 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/internal/ContentMetadataStrategyTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.encryption.s3.algorithms.AlgorithmSuite;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
public class ContentMetadataStrategyTest {
private S3Client mockS3client;
private Map<String, String> metadata = new HashMap<>();
private GetObjectResponse getObjectResponse;
private ContentMetadata expectedContentMetadata;
private GetObjectRequest getObjectRequest;
@BeforeEach
public void setUp() {
mockS3client = mock(S3Client.class);
metadata.put("x-amz-tag-len" , "128");
metadata.put("x-amz-wrap-alg" , "AES/GCM");
metadata.put("x-amz-cek-alg" , "AES/GCM/NoPadding");
metadata.put("x-amz-key-v2" , "dYHaV24t2HuNACA50fWTh2xpMDk+kpnfhHBcaEonAR3kte6WTmV9uOUxFgyVpz+2dAcJQDj6AKrxKElf");
metadata.put("x-amz-iv" , "j3GWQ0HQVDOkPDf+");
metadata.put("x-amz-matdesc" , "{}");
getObjectRequest = GetObjectRequest.builder()
.bucket("TestBucket")
.key("TestKey")
.build();
}
@Test
public void decodeWithObjectMetadata() {
getObjectResponse = GetObjectResponse.builder()
.metadata(metadata)
.build();
byte[] bytes = {-113, 113, -106, 67, 65, -48, 84, 51, -92, 60, 55, -2};
expectedContentMetadata = ContentMetadata.builder()
.algorithmSuite(AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF)
.encryptedDataKeyAlgorithm(null)
.encryptedDataKeyContext(new HashMap())
.contentIv(bytes)
.build();
ContentMetadata contentMetadata = ContentMetadataStrategy.decode(getObjectRequest, getObjectResponse);
assertEquals(expectedContentMetadata.algorithmSuite(), contentMetadata.algorithmSuite());
String actualContentIv = Arrays.toString(contentMetadata.contentIv());
String expectedContentIv = Arrays.toString(expectedContentMetadata.contentIv());
assertEquals(expectedContentIv, actualContentIv);
}
} | 2,224 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/internal/ContentMetadataTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.encryption.s3.algorithms.AlgorithmSuite;
import software.amazon.encryption.s3.materials.EncryptedDataKey;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.mockito.Mockito.mock;
public class ContentMetadataTest {
private EncryptedDataKey encryptedDataKey;
private ContentMetadata actualContentMetadata;
private String encryptedDataKeyAlgorithm;
private final Map<String, String> encryptedDataKeyContext = new HashMap<>();
private byte[] contentIv;
@BeforeEach
public void setUp() {
encryptedDataKey = mock(EncryptedDataKey.class);
contentIv = "Test String".getBytes();
encryptedDataKeyAlgorithm = "Test Algorithm";
encryptedDataKeyContext.put("testKey", "testValue");
actualContentMetadata = ContentMetadata.builder()
.algorithmSuite(AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF)
.encryptedDataKey(encryptedDataKey)
.contentIv(contentIv)
.encryptedDataKeyAlgorithm(encryptedDataKeyAlgorithm)
.encryptedDataKeyContext(encryptedDataKeyContext)
.build();
}
@Test
public void testAlgorithmSuite() {
assertEquals(AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF, actualContentMetadata.algorithmSuite());
assertNotEquals(AlgorithmSuite.ALG_AES_256_CBC_IV16_NO_KDF, actualContentMetadata.algorithmSuite());
}
@Test
public void testEncryptedDataKey() {
assertEquals(encryptedDataKey, actualContentMetadata.encryptedDataKey());
}
@Test
public void testEncryptedDataKeyAlgorithm() {
assertEquals(encryptedDataKeyAlgorithm, actualContentMetadata.encryptedDataKeyAlgorithm());
}
@Test
public void testEncryptedDataKeyContext() {
assertEquals(encryptedDataKeyContext, actualContentMetadata.encryptedDataKeyContext());
}
@Test
public void testContentIv() {
assertEquals(Arrays.toString(contentIv),Arrays.toString(actualContentMetadata.contentIv()));
}
}
| 2,225 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/internal/StreamingAesGcmContentStrategyTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
import software.amazon.encryption.s3.S3EncryptionClientException;
public class StreamingAesGcmContentStrategyTest {
@Test
public void buildStreamingAesGcmContentStrategyWithNullSecureRandomFails() {
assertThrows(S3EncryptionClientException.class, () -> StreamingAesGcmContentStrategy.builder().secureRandom(null));
}
}
| 2,226 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/internal/ApiNameVersionTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ApiNameVersionTest {
private final static String EXPECTED_API_NAME = "AmazonS3Encrypt";
private final static String EXPECTED_API_MAJOR_VERSION = "3";
@Test
public void testApiNameWithVersion() {
assertEquals(EXPECTED_API_NAME, ApiNameVersion.apiNameWithVersion().name());
// To avoid having to hardcode versions, just check that we're incrementing from 3
assertTrue(ApiNameVersion.apiNameWithVersion().version().startsWith(EXPECTED_API_MAJOR_VERSION));
}
} | 2,227 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/utils/S3EncryptionClientTestResources.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.utils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.DeleteObjectResponse;
import java.util.concurrent.CompletableFuture;
/**
* Determines which AWS resources to use while running tests.
*/
public class S3EncryptionClientTestResources {
public static final String BUCKET = System.getenv("AWS_S3EC_TEST_BUCKET");
public static final String KMS_KEY_ID = System.getenv("AWS_S3EC_TEST_KMS_KEY_ID");
// This alias must point to the same key as KMS_KEY_ID
public static final String KMS_KEY_ALIAS = System.getenv("AWS_S3EC_TEST_KMS_KEY_ALIAS");
/**
* For a given string, append a suffix to distinguish it from
* simultaneous test runs.
* @param s
* @return
*/
public static String appendTestSuffix(final String s) {
StringBuilder stringBuilder = new StringBuilder(s);
stringBuilder.append(DateTimeFormat.forPattern("-yyMMdd-hhmmss-").print(new DateTime()));
stringBuilder.append((int) (Math.random() * 100000));
return stringBuilder.toString();
}
/**
* Delete the object for the given objectKey in the given bucket.
* @param bucket the bucket to delete the object from
* @param objectKey the key of the object to delete
*/
public static void deleteObject(final String bucket, final String objectKey, final S3Client s3Client) {
s3Client.deleteObject(builder -> builder
.bucket(bucket)
.key(objectKey)
.build());
}
/**
* Delete the object for the given objectKey in the given bucket.
* @param bucket the bucket to delete the object from
* @param objectKey the key of the object to delete
*/
public static void deleteObject(final String bucket, final String objectKey, final S3AsyncClient s3Client) {
CompletableFuture<DeleteObjectResponse> response = s3Client.deleteObject(builder -> builder
.bucket(bucket)
.key(objectKey));
// Ensure completion before return
response.join();
}
}
| 2,228 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/utils/BoundedStreamBufferer.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Reads an InputStream instances into memory.
*/
public class BoundedStreamBufferer {
public static byte[] toByteArray(InputStream is, int bufferSize) throws IOException {
try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
byte[] b = new byte[bufferSize];
int n;
while ((n = is.read(b)) != -1) {
output.write(b, 0, n);
}
return output.toByteArray();
}
}
public static byte[] toByteArrayWithMarkReset(InputStream is, int bufferSize) throws IOException {
try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
byte[] b = new byte[bufferSize];
// burn some bytes to force mark/reset
byte[] discard = new byte[bufferSize];
int n;
while ((n = is.read(b)) != -1) {
is.mark(bufferSize);
is.read(discard, 0, bufferSize);
is.reset();
output.write(b, 0, n);
}
return output.toByteArray();
}
}
}
| 2,229 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/utils/BoundedInputStream.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.utils;
import java.io.InputStream;
/**
* Test utility class.
* Stream of a fixed number of printable ASCII characters.
* Useful for testing stream uploads of a specific size.
* Not threadsafe.
*/
public class BoundedInputStream extends InputStream {
private final long _bound;
private long _progress = 0;
public BoundedInputStream(final long bound) {
_bound = bound;
}
@Override
public int read() {
if (_progress >= _bound) {
return -1;
}
_progress++;
// There are 95 printable ASCII characters, starting at 32
// So take modulo 95 and add 32 to keep within that range
return ((int) (_progress % 95)) + 32;
}
}
| 2,230 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/utils/MarkResetBoundedZerosInputStream.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.utils;
import java.io.InputStream;
/**
* Test utility class.
* Stream of a fixed number of zeros. Supports arbitrary mark/reset.
* Useful for testing stream uploads of a specific size. Not threadsafe.
*/
public class MarkResetBoundedZerosInputStream extends InputStream {
private final long _boundInBytes;
private long _progress = 0;
private long _mark = 0;
public MarkResetBoundedZerosInputStream(final long boundInBytes) {
_boundInBytes = boundInBytes;
}
@Override
public int read() {
if (_progress >= _boundInBytes) {
return -1;
}
_progress++;
return 0;
}
@Override
public boolean markSupported() {
return true;
}
@Override
public void mark(int readLimit) {
// Since this InputStream implementation is bounded, we can support
// arbitrary mark/reset, so just discard the readLimit parameter.
_mark = _progress;
}
@Override
public void reset() {
_progress = _mark;
_mark = 0;
}
}
| 2,231 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/examples/MultipartUploadExampleTest.java | package software.amazon.encryption.s3.examples;
import org.junit.jupiter.api.Test;
import software.amazon.encryption.s3.utils.S3EncryptionClientTestResources;
import java.io.IOException;
public class MultipartUploadExampleTest {
@Test
public void testMultipartUploadExamples() throws IOException {
final String bucket = S3EncryptionClientTestResources.BUCKET;
MultipartUploadExample.main(new String[]{bucket});
}
}
| 2,232 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/examples/RangedGetExampleTest.java | package software.amazon.encryption.s3.examples;
import org.junit.jupiter.api.Test;
import software.amazon.encryption.s3.utils.S3EncryptionClientTestResources;
public class RangedGetExampleTest {
@Test
public void testRangedGetExamples() {
final String bucket = S3EncryptionClientTestResources.BUCKET;
RangedGetExample.main(new String[]{bucket});
}
}
| 2,233 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/examples/AsyncClientExampleTest.java | package software.amazon.encryption.s3.examples;
import org.junit.jupiter.api.Test;
import software.amazon.encryption.s3.utils.S3EncryptionClientTestResources;
public class AsyncClientExampleTest {
@Test
public void testAsyncClientExamples() {
final String bucket = S3EncryptionClientTestResources.BUCKET;
AsyncClientExample.main(new String[]{bucket});
}
}
| 2,234 |
0 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/test/java/software/amazon/encryption/s3/examples/PartialKeyPairExampleTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.examples;
import org.junit.jupiter.api.Test;
import software.amazon.encryption.s3.utils.S3EncryptionClientTestResources;
public class PartialKeyPairExampleTest {
@Test
public void testPartialKeyPairExamples() {
final String bucket = S3EncryptionClientTestResources.BUCKET;
PartialKeyPairExample.main(new String[]{bucket});
}
}
| 2,235 |
0 | Create_ds/amazon-s3-encryption-client-java/src/examples/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/examples/java/software/amazon/encryption/s3/examples/MultipartUploadExample.java | package software.amazon.encryption.s3.examples;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static software.amazon.encryption.s3.S3EncryptionClient.withAdditionalConfiguration;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.KMS_KEY_ID;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.appendTestSuffix;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.CompletedPart;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.SdkPartType;
import software.amazon.awssdk.services.s3.model.UploadPartRequest;
import software.amazon.awssdk.services.s3.model.UploadPartResponse;
import software.amazon.encryption.s3.S3EncryptionClient;
import software.amazon.encryption.s3.utils.BoundedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.IOUtils;
public class MultipartUploadExample {
public static String BUCKET;
public static void main(final String[] args) throws IOException {
BUCKET = args[0];
LowLevelMultipartUpload();
HighLevelMultipartPutObject();
}
/**
* This example demonstrates a low-level approach to performing a multipart upload to an Amazon S3 bucket
* using the S3 Client, performing encryption and decryption operations using the AWS Key Management Service (KMS).
* It showcases the process of uploading a large object in smaller parts, processing and encrypting each part,
* and then completing the multipart upload.
*
* @throws IOException If an I/O error occurs while reading or writing data.
*/
public static void LowLevelMultipartUpload() throws IOException {
final String objectKey = appendTestSuffix("low-level-multipart-upload-example");
// Overall "file" is 100MB, split into 10MB parts
final long fileSizeLimit = 1024 * 1024 * 100;
final int PART_SIZE = 10 * 1024 * 1024;
final InputStream inputStream = new BoundedInputStream(fileSizeLimit);
final InputStream objectStreamForResult = new BoundedInputStream(fileSizeLimit);
// Instantiate the S3 Encryption Client to encrypt and decrypt
// by specifying a KMS Key with the kmsKeyId builder parameter.
// enable `enableDelayedAuthenticationMode` parameter to download more than 64MB object or
// configure buffer size using `setBufferSize()` to increase your default buffer size.
//
// This means that the S3 Encryption Client can perform both encrypt and decrypt operations
// as part of the S3 putObject and getObject operations.
S3Client v3Client = S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.enableDelayedAuthenticationMode(true)
.build();
// Create Multipart upload request to S3
CreateMultipartUploadResponse initiateResult = v3Client.createMultipartUpload(builder ->
builder.bucket(BUCKET).key(objectKey));
List<CompletedPart> partETags = new ArrayList<>();
int bytesRead, bytesSent = 0;
// 10MB parts
byte[] partData = new byte[PART_SIZE];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int partsSent = 1;
// Process and Upload each part
while ((bytesRead = inputStream.read(partData, 0, partData.length)) != -1) {
outputStream.write(partData, 0, bytesRead);
if (bytesSent < PART_SIZE) {
bytesSent += bytesRead;
continue;
}
// Create UploadPartRequest for each part by specifying partNumber and
// set isLastPart as true only if the part is the last remaining part in the multipart upload.
UploadPartRequest uploadPartRequest = UploadPartRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.uploadId(initiateResult.uploadId())
.partNumber(partsSent)
.build();
final InputStream partInputStream = new ByteArrayInputStream(outputStream.toByteArray());
// Upload all the different parts of the object
UploadPartResponse uploadPartResult = v3Client.uploadPart(uploadPartRequest,
RequestBody.fromInputStream(partInputStream, partInputStream.available()));
// We need to add eTag's of all CompletedParts before calling CompleteMultipartUpload.
partETags.add(CompletedPart.builder()
.partNumber(partsSent)
.eTag(uploadPartResult.eTag())
.build());
outputStream.reset();
bytesSent = 0;
partsSent++;
}
inputStream.close();
// Set sdkPartType to SdkPartType.LAST for last part of the multipart upload.
//
// Note: Set sdkPartType parameter to SdkPartType.LAST for last part is required for Multipart Upload in S3EncryptionClient to call `cipher.doFinal()`
UploadPartRequest uploadPartRequest = UploadPartRequest.builder()
.bucket(BUCKET)
.key(objectKey)
.uploadId(initiateResult.uploadId())
.partNumber(partsSent)
.sdkPartType(SdkPartType.LAST)
.build();
// Upload the last part multipart upload to invoke `cipher.doFinal()`
final InputStream partInputStream = new ByteArrayInputStream(outputStream.toByteArray());
UploadPartResponse uploadPartResult = v3Client.uploadPart(uploadPartRequest,
RequestBody.fromInputStream(partInputStream, partInputStream.available()));
partETags.add(CompletedPart.builder()
.partNumber(partsSent)
.eTag(uploadPartResult.eTag())
.build());
// Finally call completeMultipartUpload operation to tell S3 to merge all uploaded
// parts and finish the multipart operation.
v3Client.completeMultipartUpload(builder -> builder
.bucket(BUCKET)
.key(objectKey)
.uploadId(initiateResult.uploadId())
.multipartUpload(partBuilder -> partBuilder.parts(partETags)));
// Call getObject to retrieve and decrypt the object from S3
ResponseInputStream<GetObjectResponse> output = v3Client.getObject(builder -> builder
.bucket(BUCKET)
.key(objectKey));
// Asserts
assertTrue(IOUtils.contentEquals(objectStreamForResult, output));
// Cleanup
v3Client.deleteObject(builder -> builder.bucket(BUCKET).key(objectKey));
v3Client.close();
}
/**
* This example demonstrates a high-level approach to performing a multipart object upload to an Amazon S3 bucket
* using the S3 Client, performing encryption and decryption operations using the AWS KMS Key Arn.
* This allows faster putObject by creating an on-disk encrypted copy before uploading to S3.
*
* @throws IOException If an I/O error occurs while reading or writing data.
*/
public static void HighLevelMultipartPutObject() throws IOException {
final String objectKey = appendTestSuffix("high-level-multipart-upload-example");
// Overall "file" is 100MB, split into 10MB parts
final long fileSizeLimit = 1024 * 1024 * 100;
final InputStream inputStream = new BoundedInputStream(fileSizeLimit);
final InputStream objectStreamForResult = new BoundedInputStream(fileSizeLimit);
// Instantiate the S3 Encryption Client to encrypt and decrypt
// by specifying a KMS Key with the kmsKeyId builder parameter.
// enable `enableMultipartPutObject` allows faster putObject by creating an on-disk encrypted copy before uploading to S3.
//
// This means that the S3 Encryption Client can perform both encrypt and decrypt operations
// as part of the S3 putObject and getObject operations.
// Note: You must also specify the `enableDelayedAuthenticationMode` parameter to perform getObject with more than 64MB object.
S3Client v3Client = S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.enableMultipartPutObject(true)
.enableDelayedAuthenticationMode(true)
.build();
// Create an encryption context
Map<String, String> encryptionContext = new HashMap<>();
encryptionContext.put("user-metadata-key", "user-metadata-value-v3-to-v3");
// Call putObject to encrypt the object and upload it to S3.
v3Client.putObject(builder -> builder
.bucket(BUCKET)
.overrideConfiguration(withAdditionalConfiguration(encryptionContext))
.key(objectKey), RequestBody.fromInputStream(inputStream, fileSizeLimit));
// Call getObject to retrieve and decrypt the object from S3.
ResponseInputStream<GetObjectResponse> output = v3Client.getObject(builder -> builder
.bucket(BUCKET)
.overrideConfiguration(withAdditionalConfiguration(encryptionContext))
.key(objectKey));
// Asserts
assertTrue(IOUtils.contentEquals(objectStreamForResult, output));
// Cleanup
v3Client.deleteObject(builder -> builder.bucket(BUCKET).key(objectKey));
v3Client.close();
}
}
| 2,236 |
0 | Create_ds/amazon-s3-encryption-client-java/src/examples/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/examples/java/software/amazon/encryption/s3/examples/RangedGetExample.java | package software.amazon.encryption.s3.examples;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.KMS_KEY_ID;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.appendTestSuffix;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.encryption.s3.S3EncryptionClient;
public class RangedGetExample {
// Create a 200 character input string to use as your object in the following examples.
private static final String OBJECT_CONTENT = "abcdefghijklmnopqrstABCDEFGHIJKLMNOPQRST" +
"abcdefghijklmnopqrstABCDEFGHIJKLMNOPQRST" +
"abcdefghijklmnopqrstABCDEFGHIJKLMNOPQRST" +
"abcdefghijklmnopqrstABCDEFGHIJKLMNOPQRST" +
"abcdefghijklmnopqrstABCDEFGHIJKLMNOPQRST";
public static void main(final String[] args) {
final String bucket = args[0];
simpleAesGcmV3RangedGet(bucket);
aesGcmV3RangedGetOperations(bucket);
}
/**
* This example demonstrates handling of simple ranged GET to retrieve a part of the encrypted objects.
*
* @param bucket The name of the Amazon S3 bucket to perform operations on.
*/
public static void simpleAesGcmV3RangedGet(String bucket) {
final String objectKey = appendTestSuffix("simple-v3-ranged-get-example");
// Instantiate the S3 Encryption Client by specifying an KMS Key with the kmsKeyId builder parameter.
// You must also specify the `enableLegacyUnauthenticatedModes` parameter to enable ranged GET requests.
//
// This means that the S3 Encryption Client can perform both encrypt and decrypt operations,
// and can perform ranged GET requests when a range is provided.
S3Client v3Client = S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.enableLegacyUnauthenticatedModes(true)
.build();
// Call putObject to encrypt the object and upload it to S3
v3Client.putObject(PutObjectRequest.builder()
.bucket(bucket)
.key(objectKey)
.build(), RequestBody.fromString(OBJECT_CONTENT));
// Call getObject to retrieve a range of 10-20 bytes from the object content.
ResponseBytes<GetObjectResponse> objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(bucket)
.range("bytes=10-20")
.key(objectKey));
String output = objectResponse.asUtf8String();
// Verify that the decrypted object range matches the original plaintext object at the same range.
// Note: The start and end indices of the byte range are included in the returned object.
assertEquals(OBJECT_CONTENT.substring(10, 20 + 1), output);
// Cleanup
v3Client.deleteObject(builder -> builder.bucket(bucket).key(objectKey));
v3Client.close();
}
/**
* This example demonstrates handling of various unusual ranged GET scenarios when retrieving encrypted objects.
*
* @param bucket The name of the Amazon S3 bucket to perform operations on.
*/
public static void aesGcmV3RangedGetOperations(String bucket) {
final String objectKey = appendTestSuffix("aes-gcm-v3-ranged-get-examples");
S3Client v3Client = S3EncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.enableLegacyUnauthenticatedModes(true)
.build();
// Call putObject to encrypt the object and upload it to S3
v3Client.putObject(PutObjectRequest.builder()
.bucket(bucket)
.key(objectKey)
.build(), RequestBody.fromString(OBJECT_CONTENT));
// 1. Call getObject to retrieve a range of 190-300 bytes,
// where 190 is within object range but 300 is outside the original plaintext object range.
ResponseBytes<GetObjectResponse> objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(bucket)
.range("bytes=190-300")
.key(objectKey));
String output = objectResponse.asUtf8String();
// Verify that when the start index is within object range and the end index is out of range,
// the S3 Encryption Client returns the object from the start index to the end of the original plaintext object.
assertEquals(OBJECT_CONTENT.substring(190), output);
// 2. Call getObject to retrieve a range of 100-50 bytes,
// where the start index is greater than the end index.
objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(bucket)
.range("bytes=100-50")
.key(objectKey));
output = objectResponse.asUtf8String();
// Verify that when the start index is greater than the end index,
// the S3 Encryption Client returns the entire object.
assertEquals(OBJECT_CONTENT, output);
// 3. Call getObject to retrieve a range of 10-20 bytes but with invalid format
objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(bucket)
.range("10-20")
.key(objectKey));
output = objectResponse.asUtf8String();
// Verify that when the range is specified with an invalid format,
// the S3 Encryption Client returns the entire object.
// Note: Your byte range should always be specified in the following format: "bytes=start–end"
assertEquals(OBJECT_CONTENT, output);
// 4. Call getObject to retrieve a range of 216-217 bytes.
// Both the start and end indices are greater than the original plaintext object's total length, 200.
objectResponse = v3Client.getObjectAsBytes(builder -> builder
.bucket(bucket)
.range("bytes=216-217")
.key(objectKey));
output = objectResponse.asUtf8String();
// Verify that when both the start and end indices are greater than the original plaintext object's total length,
// but still within the same cipher block, the Amazon S3 Encryption Client returns an empty object.
assertEquals("", output);
// Cleanup
v3Client.deleteObject(builder -> builder.bucket(bucket).key(objectKey));
v3Client.close();
}
}
| 2,237 |
0 | Create_ds/amazon-s3-encryption-client-java/src/examples/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/examples/java/software/amazon/encryption/s3/examples/PartialKeyPairExample.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.examples;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.Delete;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.ObjectIdentifier;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.encryption.s3.S3EncryptionClient;
import software.amazon.encryption.s3.S3EncryptionClientException;
import software.amazon.encryption.s3.materials.PartialRsaKeyPair;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.appendTestSuffix;
public class PartialKeyPairExample {
private static final String OBJECT_CONTENT = "Hello, world!";
// Use unique object keys for each example
private static final String PUBLIC_AND_PRIVATE_KEY_OBJECT_KEY = appendTestSuffix("PublicAndPrivateKeyTestObject");
private static final String PUBLIC_KEY_OBJECT_KEY = appendTestSuffix("PublicKeyTestObject");
private static final String PRIVATE_KEY_OBJECT_KEY = appendTestSuffix("PrivateKeyTestObject");
private static final Set<ObjectIdentifier> PARTIAL_KEY_PAIR_EXAMPLE_OBJECT_KEYS = Stream
.of(PUBLIC_AND_PRIVATE_KEY_OBJECT_KEY, PUBLIC_KEY_OBJECT_KEY, PRIVATE_KEY_OBJECT_KEY)
.map(k -> ObjectIdentifier.builder().key(k).build())
.collect(Collectors.toSet());
// This example generates a new key. In practice, you would
// retrieve your key from an existing keystore.
private static final KeyPair RSA_KEY_PAIR = retrieveRsaKeyPair();
public static void main(final String[] args) {
final String bucket = args[0];
useBothPublicAndPrivateKey(bucket);
useOnlyPublicKey(bucket);
useOnlyPrivateKey(bucket);
cleanup(bucket);
}
public static void useBothPublicAndPrivateKey(final String bucket) {
// Instantiate the S3 Encryption Client to encrypt and decrypt
// by specifying an RSA wrapping key pair with the rsaKeyPair builder
// parameter.
// This means that the S3 Encryption Client can perform both encrypt and decrypt operations
// as part of the S3 putObject and getObject operations.
S3Client s3Client = S3EncryptionClient.builder()
.rsaKeyPair(RSA_KEY_PAIR)
.build();
// Call putObject to encrypt the object and upload it to S3
s3Client.putObject(PutObjectRequest.builder()
.bucket(bucket)
.key(PUBLIC_AND_PRIVATE_KEY_OBJECT_KEY)
.build(), RequestBody.fromString(OBJECT_CONTENT));
// Call getObject to retrieve and decrypt the object from S3
ResponseBytes<GetObjectResponse> objectResponse = s3Client.getObjectAsBytes(builder -> builder
.bucket(bucket)
.key(PUBLIC_AND_PRIVATE_KEY_OBJECT_KEY));
String output = objectResponse.asUtf8String();
// Verify that the decrypted object matches the original plaintext object
assertEquals(OBJECT_CONTENT, output, "Decrypted response does not match original plaintext!");
// Close the client
s3Client.close();
}
static void useOnlyPublicKey(final String bucket) {
// Instantiate the S3 Encryption client to encrypt by specifying the
// public key from an RSA key pair with the PartialKeyPair object.
// When you specify the public key alone, all GetObject calls will fail
// because the private key is required to decrypt.
S3Client s3Client = S3EncryptionClient.builder()
.rsaKeyPair(new PartialRsaKeyPair(null, RSA_KEY_PAIR.getPublic()))
.build();
// Call putObject to encrypt the object and upload it to S3
s3Client.putObject(PutObjectRequest.builder()
.bucket(bucket)
.key(PUBLIC_KEY_OBJECT_KEY)
.build(), RequestBody.fromString(OBJECT_CONTENT));
// Attempt to call getObject to retrieve and decrypt the object from S3.
try {
s3Client.getObjectAsBytes(builder -> builder
.bucket(bucket)
.key(PUBLIC_KEY_OBJECT_KEY));
fail("Expected exception! No private key provided for decryption.");
} catch (final S3EncryptionClientException exception) {
// This is expected; the s3Client cannot successfully call getObject
// when instantiated with a public key.
}
// Close the client
s3Client.close();
}
static void useOnlyPrivateKey(final String bucket) {
// Instantiate the S3 Encryption client to decrypt by specifying the
// private key from an RSA key pair with the PartialRsaKeyPair object.
// When you specify the private key alone, all PutObject calls will
// fail because the public key is required to encrypt.
S3Client s3ClientPrivateKeyOnly = S3EncryptionClient.builder()
.rsaKeyPair(new PartialRsaKeyPair(RSA_KEY_PAIR.getPrivate(), null))
.build();
// Attempt to call putObject to encrypt the object and upload it to S3
try {
s3ClientPrivateKeyOnly.putObject(PutObjectRequest.builder()
.bucket(bucket)
.key(PRIVATE_KEY_OBJECT_KEY)
.build(), RequestBody.fromString(OBJECT_CONTENT));
fail("Expected exception! No public key provided for encryption.");
} catch (final S3EncryptionClientException exception) {
// This is expected; the s3Client cannot successfully call putObject
// when instantiated with a private key.
}
// Instantiate a new S3 Encryption client with a public key in order
// to successfully call PutObject so that the client which only has
// a private key can call GetObject on a valid S3 Object.
S3Client s3ClientPublicKeyOnly = S3EncryptionClient.builder()
.rsaKeyPair(new PartialRsaKeyPair(null, RSA_KEY_PAIR.getPublic()))
.build();
// Call putObject to encrypt the object and upload it to S3
s3ClientPublicKeyOnly.putObject(PutObjectRequest.builder()
.bucket(bucket)
.key(PRIVATE_KEY_OBJECT_KEY)
.build(), RequestBody.fromString(OBJECT_CONTENT));
// Call getObject to retrieve and decrypt the object from S3
ResponseBytes<GetObjectResponse> objectResponse = s3ClientPrivateKeyOnly.getObjectAsBytes(builder -> builder
.bucket(bucket)
.key(PRIVATE_KEY_OBJECT_KEY));
String output = objectResponse.asUtf8String();
// Verify that the decrypted object matches the original plaintext object
assertEquals(OBJECT_CONTENT, output, "The decrypted response does not match the original plaintext!");
// Close the clients
s3ClientPublicKeyOnly.close();
s3ClientPrivateKeyOnly.close();
}
public static void cleanup(final String bucket) {
// The S3 Encryption client is not required when deleting encrypted
// objects, use the S3 Client.
final S3Client s3Client = S3Client.builder().build();
final Delete delete = Delete.builder()
.objects(PARTIAL_KEY_PAIR_EXAMPLE_OBJECT_KEYS)
.build();
s3Client.deleteObjects(builder -> builder
.bucket(bucket)
.delete(delete)
.build());
// Close the client
s3Client.close();
}
private static KeyPair retrieveRsaKeyPair() {
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(2048);
return keyPairGen.generateKeyPair();
} catch (final NoSuchAlgorithmException exception) {
// This should be impossible, wrap with a runtime exception
throw new RuntimeException(exception);
}
}
} | 2,238 |
0 | Create_ds/amazon-s3-encryption-client-java/src/examples/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/examples/java/software/amazon/encryption/s3/examples/AsyncClientExample.java | package software.amazon.encryption.s3.examples;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.KMS_KEY_ID;
import static software.amazon.encryption.s3.utils.S3EncryptionClientTestResources.appendTestSuffix;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.encryption.s3.S3AsyncEncryptionClient;
import java.util.concurrent.CompletableFuture;
public class AsyncClientExample {
public static final String OBJECT_KEY = appendTestSuffix("async-client-example");
public static void main(final String[] args) {
String bucket = args[0];
AsyncClient(bucket);
cleanup(bucket);
}
/**
* This example demonstrates handling of an Asynchronous S3 Encryption Client for interacting with an Amazon S3 bucket, performing
* both encryption and decryption using the AWS KMS Key Arn for secure object storage.
*
* @param bucket The name of the Amazon S3 bucket to perform operations on.
*/
public static void AsyncClient(String bucket) {
final String input = "PutAsyncGetAsync";
// Instantiate the S3 Async Encryption Client to encrypt and decrypt
// by specifying an AES Key with the aesKey builder parameter.
//
// This means that the S3 Async Encryption Client can perform both encrypt and decrypt operations
// as part of the S3 putObject and getObject operations.
S3AsyncClient v3AsyncClient = S3AsyncEncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.build();
// Call putObject to encrypt the object and upload it to S3
CompletableFuture<PutObjectResponse> futurePut = v3AsyncClient.putObject(builder -> builder
.bucket(bucket)
.key(OBJECT_KEY)
.build(), AsyncRequestBody.fromString(input));
// Block on completion of the futurePut
futurePut.join();
// Call getObject to retrieve and decrypt the object from S3
CompletableFuture<ResponseBytes<GetObjectResponse>> futureGet = v3AsyncClient.getObject(builder -> builder
.bucket(bucket)
.key(OBJECT_KEY)
.build(), AsyncResponseTransformer.toBytes());
// Just wait for the future to complete
ResponseBytes<GetObjectResponse> getResponse = futureGet.join();
// Assert
assertEquals(input, getResponse.asUtf8String());
// Close the client
v3AsyncClient.close();
}
private static void cleanup(String bucket) {
// Instantiate the client to delete object
S3AsyncClient v3Client = S3AsyncEncryptionClient.builder()
.kmsKeyId(KMS_KEY_ID)
.build();
// Call deleteObject to delete the object from given S3 Bucket
v3Client.deleteObject(builder -> builder.bucket(bucket)
.key(OBJECT_KEY)).join();
// Close the client
v3Client.close();
}
}
| 2,239 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/S3EncryptionClientSecurityException.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3;
public class S3EncryptionClientSecurityException extends S3EncryptionClientException {
public S3EncryptionClientSecurityException(String message) {
super(message);
}
public S3EncryptionClientSecurityException(String message, Throwable cause) {
super(message, cause);
}
}
| 2,240 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/S3EncryptionClientException.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3;
import software.amazon.awssdk.core.exception.SdkClientException;
public class S3EncryptionClientException extends SdkClientException {
public S3EncryptionClientException(String message) {
super(SdkClientException.builder()
.message(message));
}
public S3EncryptionClientException(String message, Throwable cause) {
super(SdkClientException.builder()
.message(message)
.cause(cause));
}
}
| 2,241 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/S3AsyncEncryptionClient.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.services.s3.DelegatingS3AsyncClient;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.internal.crt.S3CrtAsyncClient;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectResponse;
import software.amazon.awssdk.services.s3.model.DeleteObjectsRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectsResponse;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.ObjectIdentifier;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.services.s3.model.S3Request;
import software.amazon.encryption.s3.internal.GetEncryptedObjectPipeline;
import software.amazon.encryption.s3.internal.NoRetriesAsyncRequestBody;
import software.amazon.encryption.s3.internal.PutEncryptedObjectPipeline;
import software.amazon.encryption.s3.materials.AesKeyring;
import software.amazon.encryption.s3.materials.CryptographicMaterialsManager;
import software.amazon.encryption.s3.materials.DefaultCryptoMaterialsManager;
import software.amazon.encryption.s3.materials.Keyring;
import software.amazon.encryption.s3.materials.KmsKeyring;
import software.amazon.encryption.s3.materials.PartialRsaKeyPair;
import software.amazon.encryption.s3.materials.RsaKeyring;
import javax.crypto.SecretKey;
import java.security.KeyPair;
import java.security.Provider;
import java.security.SecureRandom;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.Function;
import static software.amazon.encryption.s3.S3EncryptionClientUtilities.DEFAULT_BUFFER_SIZE_BYTES;
import static software.amazon.encryption.s3.S3EncryptionClientUtilities.MAX_ALLOWED_BUFFER_SIZE_BYTES;
import static software.amazon.encryption.s3.S3EncryptionClientUtilities.MIN_ALLOWED_BUFFER_SIZE_BYTES;
import static software.amazon.encryption.s3.internal.ApiNameVersion.API_NAME_INTERCEPTOR;
/**
* This client is a drop-in replacement for the S3 Async client. It will automatically encrypt objects
* on putObject and decrypt objects on getObject using the provided encryption key(s).
*/
public class S3AsyncEncryptionClient extends DelegatingS3AsyncClient {
private final S3AsyncClient _wrappedClient;
private final CryptographicMaterialsManager _cryptoMaterialsManager;
private final SecureRandom _secureRandom;
private final boolean _enableLegacyUnauthenticatedModes;
private final boolean _enableDelayedAuthenticationMode;
private final boolean _enableMultipartPutObject;
private final long _bufferSize;
private S3AsyncEncryptionClient(Builder builder) {
super(builder._wrappedClient);
_wrappedClient = builder._wrappedClient;
_cryptoMaterialsManager = builder._cryptoMaterialsManager;
_secureRandom = builder._secureRandom;
_enableLegacyUnauthenticatedModes = builder._enableLegacyUnauthenticatedModes;
_enableDelayedAuthenticationMode = builder._enableDelayedAuthenticationMode;
_enableMultipartPutObject = builder._enableMultipartPutObject;
_bufferSize = builder._bufferSize;
}
/**
* Creates a builder that can be used to configure and create a {@link S3AsyncEncryptionClient}.
*/
public static Builder builder() {
return new Builder();
}
/**
* Attaches encryption context to a request. Must be used as a parameter to
* {@link S3Request#overrideConfiguration()} in the request.
* Encryption context can be used to enforce authentication of ciphertext.
* The same encryption context used to encrypt MUST be provided on decrypt.
* Encryption context is only supported with KMS keys.
* @param encryptionContext the encryption context to use for the request.
* @return Consumer for use in overrideConfiguration()
*/
public static Consumer<AwsRequestOverrideConfiguration.Builder> withAdditionalEncryptionContext(Map<String, String> encryptionContext) {
return builder ->
builder.putExecutionAttribute(S3EncryptionClient.ENCRYPTION_CONTEXT, encryptionContext);
}
/**
* See {@link S3AsyncClient#putObject(PutObjectRequest, AsyncRequestBody)}.
* <p>
* In the S3AsyncEncryptionClient, putObject encrypts the data in the requestBody as it is
* written to S3.
* </p>
* @param putObjectRequest the request instance
* @param requestBody
* Functional interface that can be implemented to produce the request content in a non-blocking manner. The
* size of the content is expected to be known up front. See {@link AsyncRequestBody} for specific details on
* implementing this interface as well as links to precanned implementations for common scenarios like
* uploading from a file.
* @return A Java Future containing the result of the PutObject operation returned by the service.
* <p>
* The CompletableFuture returned by this method can be completed exceptionally with the following
* exceptions.
* <ul>
* <li>SdkException Base class for all exceptions that can be thrown by the SDK (both service and client).
* Can be used for catch all scenarios.</li>
* <li>SdkClientException If any client side error occurs such as an IO related failure, failure to get
* credentials, etc.</li>
* <li>S3EncryptionClientException Base class for all encryption client specific exceptions.</li>
* </ul>
*/
@Override
public CompletableFuture<PutObjectResponse> putObject(PutObjectRequest putObjectRequest, AsyncRequestBody requestBody)
throws AwsServiceException, SdkClientException {
if (_enableMultipartPutObject) {
return multipartPutObject(putObjectRequest, requestBody);
}
PutEncryptedObjectPipeline pipeline = PutEncryptedObjectPipeline.builder()
.s3AsyncClient(_wrappedClient)
.cryptoMaterialsManager(_cryptoMaterialsManager)
.secureRandom(_secureRandom)
.build();
return pipeline.putObject(putObjectRequest, requestBody);
}
private CompletableFuture<PutObjectResponse> multipartPutObject(PutObjectRequest putObjectRequest, AsyncRequestBody requestBody) {
S3AsyncClient crtClient;
if (_wrappedClient instanceof S3CrtAsyncClient) {
// if the wrappedClient is a CRT, use it
crtClient = _wrappedClient;
} else {
// else create a default one
crtClient = S3AsyncClient.crtCreate();
}
PutEncryptedObjectPipeline pipeline = PutEncryptedObjectPipeline.builder()
.s3AsyncClient(crtClient)
.cryptoMaterialsManager(_cryptoMaterialsManager)
.secureRandom(_secureRandom)
.build();
// Ensures parts are not retried to avoid corrupting ciphertext
AsyncRequestBody noRetryBody = new NoRetriesAsyncRequestBody(requestBody);
return pipeline.putObject(putObjectRequest, noRetryBody);
}
/**
* See {@link S3AsyncClient#getObject(GetObjectRequest, AsyncResponseTransformer)}
* <p>
* In the S3AsyncEncryptionClient, getObject decrypts the data as it is read from S3.
* </p>
* @param getObjectRequest the request instance.
* @param asyncResponseTransformer
* The response transformer for processing the streaming response in a non-blocking manner. See
* {@link AsyncResponseTransformer} for details on how this callback should be implemented and for links to
* precanned implementations for common scenarios like downloading to a file.
* @return A future to the transformed result of the AsyncResponseTransformer.
* <p>
* The CompletableFuture returned by this method can be completed exceptionally with the following
* exceptions.
* <ul>
* <li>NoSuchKeyException The specified key does not exist.</li>
* <li>InvalidObjectStateException Object is archived and inaccessible until restored.</li>
* <li>SdkException Base class for all exceptions that can be thrown by the SDK (both service and client).
* Can be used for catch all scenarios.</li>
* <li>SdkClientException If any client side error occurs such as an IO related failure, failure to get
* credentials, etc.</li>
* <li>S3EncryptionClientException Base class for all encryption client exceptions.</li>
* </ul>
*/
@Override
public <T> CompletableFuture<T> getObject(GetObjectRequest getObjectRequest,
AsyncResponseTransformer<GetObjectResponse, T> asyncResponseTransformer) {
GetEncryptedObjectPipeline pipeline = GetEncryptedObjectPipeline.builder()
.s3AsyncClient(_wrappedClient)
.cryptoMaterialsManager(_cryptoMaterialsManager)
.enableLegacyUnauthenticatedModes(_enableLegacyUnauthenticatedModes)
.enableDelayedAuthentication(_enableDelayedAuthenticationMode)
.bufferSize(_bufferSize)
.build();
return pipeline.getObject(getObjectRequest, asyncResponseTransformer);
}
/**
* See {@link S3AsyncClient#deleteObject(DeleteObjectRequest)}.
* <p>
* In the S3 Encryption Client, deleteObject also deletes the instruction file,
* if present.
* </p>
* @param deleteObjectRequest the request instance
* @return A Java Future containing the result of the DeleteObject operation returned by the service.
*/
@Override
public CompletableFuture<DeleteObjectResponse> deleteObject(DeleteObjectRequest deleteObjectRequest) {
final DeleteObjectRequest actualRequest = deleteObjectRequest.toBuilder()
.overrideConfiguration(API_NAME_INTERCEPTOR)
.build();
final CompletableFuture<DeleteObjectResponse> response = _wrappedClient.deleteObject(actualRequest);
final String instructionObjectKey = deleteObjectRequest.key() + ".instruction";
final CompletableFuture<DeleteObjectResponse> instructionResponse = _wrappedClient.deleteObject(builder -> builder
.overrideConfiguration(API_NAME_INTERCEPTOR)
.bucket(deleteObjectRequest.bucket())
.key(instructionObjectKey));
// Delete the instruction file, then delete the object
Function<DeleteObjectResponse, DeleteObjectResponse> deletion = deleteObjectResponse ->
response.join();
return instructionResponse.thenApplyAsync(deletion);
}
/**
* See {@link S3AsyncClient#deleteObjects(DeleteObjectsRequest)}.
* <p>
* In the S3 Encryption Client, deleteObjects also deletes the instruction file(s),
* if present.
* </p>
* @param deleteObjectsRequest the request instance
* @return A Java Future containing the result of the DeleteObjects operation returned by the service.
*/
@Override
public CompletableFuture<DeleteObjectsResponse> deleteObjects(DeleteObjectsRequest deleteObjectsRequest) throws AwsServiceException,
SdkClientException {
// Add the instruction file keys to the list of objects to delete
final List<ObjectIdentifier> objectsToDelete = S3EncryptionClientUtilities.instructionFileKeysToDelete(deleteObjectsRequest);
// Add the original objects
objectsToDelete.addAll(deleteObjectsRequest.delete().objects());
return _wrappedClient.deleteObjects(deleteObjectsRequest.toBuilder()
.overrideConfiguration(API_NAME_INTERCEPTOR)
.delete(builder -> builder.objects(objectsToDelete))
.build());
}
/**
* Closes the wrapped {@link S3AsyncClient} instance.
*/
@Override
public void close() {
_wrappedClient.close();
}
// This is very similar to the S3EncryptionClient builder
// Make sure to keep both clients in mind when adding new builder options
public static class Builder {
private S3AsyncClient _wrappedClient = S3AsyncClient.builder().build();
private CryptographicMaterialsManager _cryptoMaterialsManager;
private Keyring _keyring;
private SecretKey _aesKey;
private PartialRsaKeyPair _rsaKeyPair;
private String _kmsKeyId;
private boolean _enableLegacyWrappingAlgorithms = false;
private boolean _enableLegacyUnauthenticatedModes = false;
private boolean _enableDelayedAuthenticationMode = false;
private boolean _enableMultipartPutObject = false;
private Provider _cryptoProvider = null;
private SecureRandom _secureRandom = new SecureRandom();
private long _bufferSize = -1L;
private Builder() {
}
/**
* Specifies the wrapped client to use for the actual S3 request.
* This client will be used for all async operations.
* You can pass any S3AsyncClient implementation (e.g. the CRT
* client), but you cannot pass an S3AsyncEncryptionClient.
* @param wrappedClient the client to use for S3 operations.
* @return Returns a reference to this object so that method calls can be chained together.
*/
/*
* Note that this does NOT create a defensive clone of S3Client. Any modifications made to the wrapped
* S3Client will be reflected in this Builder.
*/
@SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "Pass mutability into wrapping client")
public Builder wrappedClient(S3AsyncClient wrappedClient) {
if (wrappedClient instanceof S3AsyncEncryptionClient) {
throw new S3EncryptionClientException("Cannot use S3EncryptionClient as wrapped client");
}
this._wrappedClient = wrappedClient;
return this;
}
/**
* Specifies the {@link CryptographicMaterialsManager} to use for managing key wrapping keys.
* @param cryptoMaterialsManager the CMM to use
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder cryptoMaterialsManager(CryptographicMaterialsManager cryptoMaterialsManager) {
this._cryptoMaterialsManager = cryptoMaterialsManager;
checkKeyOptions();
return this;
}
/**
* Specifies the {@link Keyring} to use for key wrapping and unwrapping.
* @param keyring the Keyring instance to use
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder keyring(Keyring keyring) {
this._keyring = keyring;
checkKeyOptions();
return this;
}
/**
* Specifies a "raw" AES key to use for key wrapping/unwrapping.
* @param aesKey the AES key as a {@link SecretKey} instance
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder aesKey(SecretKey aesKey) {
this._aesKey = aesKey;
checkKeyOptions();
return this;
}
/**
* Specifies a "raw" RSA key pair to use for key wrapping/unwrapping.
* @param rsaKeyPair the RSA key pair as a {@link KeyPair} instance
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder rsaKeyPair(KeyPair rsaKeyPair) {
this._rsaKeyPair = new PartialRsaKeyPair(rsaKeyPair);
checkKeyOptions();
return this;
}
/**
* Specifies a "raw" RSA key pair to use for key wrapping/unwrapping.
* This option takes a {@link PartialRsaKeyPair} instance, which allows
* either a public key (decryption only) or private key (encryption only)
* rather than requiring both parts.
* @param partialRsaKeyPair the RSA key pair as a {@link PartialRsaKeyPair} instance
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder rsaKeyPair(PartialRsaKeyPair partialRsaKeyPair) {
this._rsaKeyPair = partialRsaKeyPair;
checkKeyOptions();
return this;
}
/**
* Specifies a KMS key to use for key wrapping/unwrapping. Any valid KMS key
* identifier (including the full ARN or an alias ARN) is permitted. When
* decrypting objects, the key referred to by this KMS key identifier is
* always used.
* @param kmsKeyId the KMS key identifier as a {@link String} instance
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder kmsKeyId(String kmsKeyId) {
this._kmsKeyId = kmsKeyId;
checkKeyOptions();
return this;
}
// We only want one way to use a key, if more than one is set, throw an error
private void checkKeyOptions() {
if (onlyOneNonNull(_cryptoMaterialsManager, _keyring, _aesKey, _rsaKeyPair, _kmsKeyId)) {
return;
}
throw new S3EncryptionClientException("Only one may be set of: crypto materials manager, keyring, AES key, RSA key pair, KMS key id");
}
private boolean onlyOneNonNull(Object... values) {
boolean haveOneNonNull = false;
for (Object o : values) {
if (o != null) {
if (haveOneNonNull) {
return false;
}
haveOneNonNull = true;
}
}
return haveOneNonNull;
}
/**
* When set to true, decryption of objects using legacy key wrapping
* modes is enabled.
* @param shouldEnableLegacyWrappingAlgorithms true to enable legacy wrapping algorithms
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder enableLegacyWrappingAlgorithms(boolean shouldEnableLegacyWrappingAlgorithms) {
this._enableLegacyWrappingAlgorithms = shouldEnableLegacyWrappingAlgorithms;
return this;
}
/**
* When set to true, decryption of content using legacy encryption algorithms
* is enabled. This includes use of GetObject requests with a range, as this
* mode is not authenticated.
* @param shouldEnableLegacyUnauthenticatedModes true to enable legacy content algorithms
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder enableLegacyUnauthenticatedModes(boolean shouldEnableLegacyUnauthenticatedModes) {
this._enableLegacyUnauthenticatedModes = shouldEnableLegacyUnauthenticatedModes;
return this;
}
/**
* When set to true, authentication of streamed objects is delayed until the
* entire object is read from the stream. When this mode is enabled, the consuming
* application must support a way to invalidate any data read from the stream as
* the tag will not be validated until the stream is read to completion, as the
* integrity of the data cannot be ensured. See the AWS Documentation for more
* information.
* @param shouldEnableDelayedAuthenticationMode true to enable delayed authentication
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder enableDelayedAuthenticationMode(boolean shouldEnableDelayedAuthenticationMode) {
this._enableDelayedAuthenticationMode = shouldEnableDelayedAuthenticationMode;
return this;
}
/**
* When set to true, the putObject method will use multipart upload to perform
* the upload. Disabled by default.
* @param _enableMultipartPutObject true enables the multipart upload implementation of putObject
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder enableMultipartPutObject(boolean _enableMultipartPutObject) {
this._enableMultipartPutObject = _enableMultipartPutObject;
return this;
}
/**
* Sets the buffer size for safe authentication used when delayed authentication mode is disabled.
* If buffer size is not given during client configuration, default buffer size is set to 64MiB.
* @param bufferSize the desired buffer size in Bytes.
* @return Returns a reference to this object so that method calls can be chained together.
* @throws S3EncryptionClientException if the specified buffer size is outside the allowed bounds
*/
public Builder setBufferSize(long bufferSize) {
if (bufferSize < MIN_ALLOWED_BUFFER_SIZE_BYTES || bufferSize > MAX_ALLOWED_BUFFER_SIZE_BYTES) {
throw new S3EncryptionClientException("Invalid buffer size: " + bufferSize + " Bytes. Buffer size must be between " + MIN_ALLOWED_BUFFER_SIZE_BYTES + " and " + MAX_ALLOWED_BUFFER_SIZE_BYTES + " Bytes.");
}
this._bufferSize = bufferSize;
return this;
}
/**
* Allows the user to pass an instance of {@link Provider} to be used
* for cryptographic operations. By default, the S3 Encryption Client
* will use the first compatible {@link Provider} in the chain. When this option
* is used, the given provider will be used for all cryptographic operations.
* If the provider is missing a required algorithm suite, e.g. AES-GCM, then
* operations may fail.
* Advanced option. Users who configure a {@link Provider} are responsible
* for the security and correctness of the provider.
* @param cryptoProvider the {@link Provider to always use}
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder cryptoProvider(Provider cryptoProvider) {
this._cryptoProvider = cryptoProvider;
return this;
}
/**
* Allows the user to pass an instance of {@link SecureRandom} to be used
* for generating keys and IVs. Advanced option. Users who provide a {@link SecureRandom}
* are responsible for the security and correctness of the {@link SecureRandom} implementation.
* @param secureRandom the {@link SecureRandom} instance to use
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder secureRandom(SecureRandom secureRandom) {
if (secureRandom == null) {
throw new S3EncryptionClientException("SecureRandom provided to S3EncryptionClient cannot be null");
}
_secureRandom = secureRandom;
return this;
}
/**
* Validates and builds the S3AsyncEncryptionClient according
* to the configuration options passed to the Builder object.
* @return an instance of the S3AsyncEncryptionClient
*/
public S3AsyncEncryptionClient build() {
if (!onlyOneNonNull(_cryptoMaterialsManager, _keyring, _aesKey, _rsaKeyPair, _kmsKeyId)) {
throw new S3EncryptionClientException("Exactly one must be set of: crypto materials manager, keyring, AES key, RSA key pair, KMS key id");
}
if (_bufferSize >= 0) {
if (_enableDelayedAuthenticationMode) {
throw new S3EncryptionClientException("Buffer size cannot be set when delayed authentication mode is enabled");
}
} else {
_bufferSize = DEFAULT_BUFFER_SIZE_BYTES;
}
if (_keyring == null) {
if (_aesKey != null) {
_keyring = AesKeyring.builder()
.wrappingKey(_aesKey)
.enableLegacyWrappingAlgorithms(_enableLegacyWrappingAlgorithms)
.secureRandom(_secureRandom)
.build();
} else if (_rsaKeyPair != null) {
_keyring = RsaKeyring.builder()
.wrappingKeyPair(_rsaKeyPair)
.enableLegacyWrappingAlgorithms(_enableLegacyWrappingAlgorithms)
.secureRandom(_secureRandom)
.build();
} else if (_kmsKeyId != null) {
_keyring = KmsKeyring.builder()
.wrappingKeyId(_kmsKeyId)
.enableLegacyWrappingAlgorithms(_enableLegacyWrappingAlgorithms)
.secureRandom(_secureRandom)
.build();
}
}
if (_cryptoMaterialsManager == null) {
_cryptoMaterialsManager = DefaultCryptoMaterialsManager.builder()
.keyring(_keyring)
.cryptoProvider(_cryptoProvider)
.build();
}
return new S3AsyncEncryptionClient(this);
}
}
}
| 2,242 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/S3EncryptionClientUtilities.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3;
import software.amazon.awssdk.services.s3.model.DeleteObjectsRequest;
import software.amazon.awssdk.services.s3.model.ObjectIdentifier;
import software.amazon.encryption.s3.algorithms.AlgorithmSuite;
import java.util.List;
import java.util.stream.Collectors;
/**
* This class contains that which can be shared between the default S3 Encryption
* Client and its Async counterpart.
*/
public class S3EncryptionClientUtilities {
public static final String INSTRUCTION_FILE_SUFFIX = ".instruction";
public static final long MIN_ALLOWED_BUFFER_SIZE_BYTES = AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF.cipherBlockSizeBytes();
public static final long MAX_ALLOWED_BUFFER_SIZE_BYTES = AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF.cipherMaxContentLengthBytes();
/**
* The Default Buffer Size for Safe authentication is set to 64MiB.
*/
public static final long DEFAULT_BUFFER_SIZE_BYTES = 64 * 1024 * 1024;
/**
* For a given DeleteObjectsRequest, return a list of ObjectIdentifiers
* representing the corresponding instruction files to delete.
* @param request a DeleteObjectsRequest
* @return the list of ObjectIdentifiers for instruction files to delete
*/
static List<ObjectIdentifier> instructionFileKeysToDelete(final DeleteObjectsRequest request) {
return request.delete().objects().stream()
.map(o -> o.toBuilder().key(o.key() + INSTRUCTION_FILE_SUFFIX).build())
.collect(Collectors.toList());
}
}
| 2,243 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/S3EncryptionClient.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.interceptor.ExecutionAttribute;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.services.s3.DelegatingS3Client;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.AbortMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.CompletedPart;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectResponse;
import software.amazon.awssdk.services.s3.model.DeleteObjectsRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectsResponse;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.ObjectIdentifier;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.services.s3.model.S3Request;
import software.amazon.awssdk.services.s3.model.UploadPartRequest;
import software.amazon.awssdk.services.s3.model.UploadPartResponse;
import software.amazon.encryption.s3.algorithms.AlgorithmSuite;
import software.amazon.encryption.s3.internal.GetEncryptedObjectPipeline;
import software.amazon.encryption.s3.internal.MultiFileOutputStream;
import software.amazon.encryption.s3.internal.MultipartUploadObjectPipeline;
import software.amazon.encryption.s3.internal.PutEncryptedObjectPipeline;
import software.amazon.encryption.s3.internal.UploadObjectObserver;
import software.amazon.encryption.s3.materials.AesKeyring;
import software.amazon.encryption.s3.materials.CryptographicMaterialsManager;
import software.amazon.encryption.s3.materials.DefaultCryptoMaterialsManager;
import software.amazon.encryption.s3.materials.Keyring;
import software.amazon.encryption.s3.materials.KmsKeyring;
import software.amazon.encryption.s3.materials.MultipartConfiguration;
import software.amazon.encryption.s3.materials.PartialRsaKeyPair;
import software.amazon.encryption.s3.materials.RsaKeyring;
import javax.crypto.SecretKey;
import java.io.IOException;
import java.security.KeyPair;
import java.security.Provider;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Consumer;
import static software.amazon.encryption.s3.S3EncryptionClientUtilities.DEFAULT_BUFFER_SIZE_BYTES;
import static software.amazon.encryption.s3.S3EncryptionClientUtilities.INSTRUCTION_FILE_SUFFIX;
import static software.amazon.encryption.s3.S3EncryptionClientUtilities.MAX_ALLOWED_BUFFER_SIZE_BYTES;
import static software.amazon.encryption.s3.S3EncryptionClientUtilities.MIN_ALLOWED_BUFFER_SIZE_BYTES;
import static software.amazon.encryption.s3.S3EncryptionClientUtilities.instructionFileKeysToDelete;
import static software.amazon.encryption.s3.internal.ApiNameVersion.API_NAME_INTERCEPTOR;
/**
* This client is a drop-in replacement for the S3 client. It will automatically encrypt objects
* on putObject and decrypt objects on getObject using the provided encryption key(s).
*/
public class S3EncryptionClient extends DelegatingS3Client {
// Used for request-scoped encryption contexts for supporting keys
public static final ExecutionAttribute<Map<String, String>> ENCRYPTION_CONTEXT = new ExecutionAttribute<>("EncryptionContext");
public static final ExecutionAttribute<MultipartConfiguration> CONFIGURATION = new ExecutionAttribute<>("MultipartConfiguration");
private final S3Client _wrappedClient;
private final S3AsyncClient _wrappedAsyncClient;
private final CryptographicMaterialsManager _cryptoMaterialsManager;
private final SecureRandom _secureRandom;
private final boolean _enableLegacyUnauthenticatedModes;
private final boolean _enableDelayedAuthenticationMode;
private final boolean _enableMultipartPutObject;
private final MultipartUploadObjectPipeline _multipartPipeline;
private final long _bufferSize;
private S3EncryptionClient(Builder builder) {
super(builder._wrappedClient);
_wrappedClient = builder._wrappedClient;
_wrappedAsyncClient = builder._wrappedAsyncClient;
_cryptoMaterialsManager = builder._cryptoMaterialsManager;
_secureRandom = builder._secureRandom;
_enableLegacyUnauthenticatedModes = builder._enableLegacyUnauthenticatedModes;
_enableDelayedAuthenticationMode = builder._enableDelayedAuthenticationMode;
_enableMultipartPutObject = builder._enableMultipartPutObject;
_multipartPipeline = builder._multipartPipeline;
_bufferSize = builder._bufferSize;
}
/**
* Creates a builder that can be used to configure and create a {@link S3EncryptionClient}.
*/
public static Builder builder() {
return new Builder();
}
/**
* Attaches encryption context to a request. Must be used as a parameter to
* {@link S3Request#overrideConfiguration()} in the request.
* Encryption context can be used to enforce authentication of ciphertext.
* The same encryption context used to encrypt MUST be provided on decrypt.
* Encryption context is only supported with KMS keys.
* @param encryptionContext the encryption context to use for the request.
* @return Consumer for use in overrideConfiguration()
*/
public static Consumer<AwsRequestOverrideConfiguration.Builder> withAdditionalConfiguration(Map<String, String> encryptionContext) {
return builder ->
builder.putExecutionAttribute(S3EncryptionClient.ENCRYPTION_CONTEXT, encryptionContext);
}
/**
* Attaches multipart configuration to a request. Must be used as a parameter to
* {@link S3Request#overrideConfiguration()} in the request.
* @param multipartConfiguration the {@link MultipartConfiguration} instance to use
* @return Consumer for use in overrideConfiguration()
*/
public static Consumer<AwsRequestOverrideConfiguration.Builder> withAdditionalConfiguration(MultipartConfiguration multipartConfiguration) {
return builder ->
builder.putExecutionAttribute(S3EncryptionClient.CONFIGURATION, multipartConfiguration);
}
/**
* Attaches encryption context and multipart configuration to a request.
* * Must be used as a parameter to
* {@link S3Request#overrideConfiguration()} in the request.
* Encryption context can be used to enforce authentication of ciphertext.
* The same encryption context used to encrypt MUST be provided on decrypt.
* Encryption context is only supported with KMS keys.
* @param encryptionContext the encryption context to use for the request.
* @param multipartConfiguration the {@link MultipartConfiguration} instance to use
* @return Consumer for use in overrideConfiguration()
*/
public static Consumer<AwsRequestOverrideConfiguration.Builder> withAdditionalConfiguration(Map<String, String> encryptionContext, MultipartConfiguration multipartConfiguration) {
return builder ->
builder.putExecutionAttribute(S3EncryptionClient.ENCRYPTION_CONTEXT, encryptionContext)
.putExecutionAttribute(S3EncryptionClient.CONFIGURATION, multipartConfiguration);
}
/**
* See {@link S3EncryptionClient#putObject(PutObjectRequest, RequestBody)}.
* <p>
* In the S3EncryptionClient, putObject encrypts the data in the requestBody as it is
* written to S3.
* </p>
* @param putObjectRequest the request instance
* @param requestBody
* The content to send to the service. A {@link RequestBody} can be created using one of several factory
* methods for various sources of data. For example, to create a request body from a file you can do the
* following.
* @return Result of the PutObject operation returned by the service.
* @throws SdkClientException If any client side error occurs such as an IO related failure, failure to get credentials, etc.
* @throws S3EncryptionClientException Base class for all encryption client exceptions.
*/
@Override
public PutObjectResponse putObject(PutObjectRequest putObjectRequest, RequestBody requestBody)
throws AwsServiceException, SdkClientException {
if (_enableMultipartPutObject) {
try {
CompleteMultipartUploadResponse completeResponse = multipartPutObject(putObjectRequest, requestBody);
PutObjectResponse response = PutObjectResponse.builder()
.eTag(completeResponse.eTag())
.build();
return response;
} catch (Throwable e) {
throw new S3EncryptionClientException("Exception while performing Multipart Upload PutObject", e);
}
}
PutEncryptedObjectPipeline pipeline = PutEncryptedObjectPipeline.builder()
.s3AsyncClient(_wrappedAsyncClient)
.cryptoMaterialsManager(_cryptoMaterialsManager)
.secureRandom(_secureRandom)
.build();
try {
CompletableFuture<PutObjectResponse> futurePut = pipeline.putObject(putObjectRequest, AsyncRequestBody.fromInputStream(requestBody.contentStreamProvider().newStream(), requestBody.optionalContentLength().orElse(-1L), Executors.newSingleThreadExecutor()));
return futurePut.join();
} catch (CompletionException completionException) {
throw new S3EncryptionClientException(completionException.getMessage(), completionException.getCause());
} catch (Exception exception) {
throw new S3EncryptionClientException(exception.getMessage(), exception);
}
}
/**
* See {@link S3EncryptionClient#getObject(GetObjectRequest, ResponseTransformer)}
* <p>
* In the S3EncryptionClient, getObject decrypts the data as it is read from S3.
* </p>
* @param getObjectRequest the request instance
* @param responseTransformer
* Functional interface for processing the streamed response content. The unmarshalled GetObjectResponse and
* an InputStream to the response content are provided as parameters to the callback. The callback may return
* a transformed type which will be the return value of this method. See
* {@link software.amazon.awssdk.core.sync.ResponseTransformer} for details on implementing this interface
* and for links to pre-canned implementations for common scenarios like downloading to a file.
* @return The transformed result of the ResponseTransformer.
* @throws SdkClientException If any client side error occurs such as an IO related failure, failure to get credentials, etc.
* @throws S3EncryptionClientException Base class for all encryption client exceptions.
*/
@Override
public <T> T getObject(GetObjectRequest getObjectRequest,
ResponseTransformer<GetObjectResponse, T> responseTransformer)
throws AwsServiceException, SdkClientException {
GetEncryptedObjectPipeline pipeline = GetEncryptedObjectPipeline.builder()
.s3AsyncClient(_wrappedAsyncClient)
.cryptoMaterialsManager(_cryptoMaterialsManager)
.enableLegacyUnauthenticatedModes(_enableLegacyUnauthenticatedModes)
.enableDelayedAuthentication(_enableDelayedAuthenticationMode)
.bufferSize(_bufferSize)
.build();
try {
ResponseInputStream<GetObjectResponse> joinFutureGet = pipeline.getObject(getObjectRequest, AsyncResponseTransformer.toBlockingInputStream()).join();
return responseTransformer.transform(joinFutureGet.response(), AbortableInputStream.create(joinFutureGet));
} catch (CompletionException e) {
throw new S3EncryptionClientException(e.getCause().getMessage(), e.getCause());
} catch (Exception e) {
throw new S3EncryptionClientException("Unable to transform response.", e);
}
}
private CompleteMultipartUploadResponse multipartPutObject(PutObjectRequest request, RequestBody requestBody) throws Throwable {
// Similar logic exists in the MultipartUploadObjectPipeline,
// but the request types do not match so refactoring is not possible
final long contentLength;
if (request.contentLength() != null) {
if (requestBody.optionalContentLength().isPresent() && !request.contentLength().equals(requestBody.optionalContentLength().get())) {
// if the contentLength values do not match, throw an exception, since we don't know which is correct
throw new S3EncryptionClientException("The contentLength provided in the request object MUST match the " +
"contentLength in the request body");
} else if (!requestBody.optionalContentLength().isPresent()) {
// no contentLength in request body, use the one in request
contentLength = request.contentLength();
} else {
// only remaining case is when the values match, so either works here
contentLength = request.contentLength();
}
} else {
contentLength = requestBody.optionalContentLength().orElse(-1L);
}
if (contentLength > AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF.cipherMaxContentLengthBytes()) {
throw new S3EncryptionClientException("The contentLength of the object you are attempting to encrypt exceeds" +
"the maximum length allowed for GCM encryption.");
}
MultipartConfiguration multipartConfiguration;
// If MultipartConfiguration is null, Initialize MultipartConfiguration
if (request.overrideConfiguration().isPresent()) {
multipartConfiguration = request.overrideConfiguration().get()
.executionAttributes()
.getOptionalAttribute(S3EncryptionClient.CONFIGURATION)
.orElse(MultipartConfiguration.builder().build());
} else {
multipartConfiguration = MultipartConfiguration.builder().build();
}
ExecutorService es = multipartConfiguration.executorService();
final boolean defaultExecutorService = es == null;
if (es == null) {
throw new S3EncryptionClientException("ExecutorService should not be null, Please initialize during MultipartConfiguration");
}
UploadObjectObserver observer = multipartConfiguration.uploadObjectObserver();
if (observer == null) {
throw new S3EncryptionClientException("UploadObjectObserver should not be null, Please initialize during MultipartConfiguration");
}
observer.init(request, _wrappedAsyncClient, this, es);
final String uploadId = observer.onUploadCreation(request);
final List<CompletedPart> partETags = new ArrayList<>();
MultiFileOutputStream outputStream = multipartConfiguration.multiFileOutputStream();
if (outputStream == null) {
throw new S3EncryptionClientException("MultiFileOutputStream should not be null, Please initialize during MultipartConfiguration");
}
try {
// initialize the multi-file output stream
outputStream.init(observer, multipartConfiguration.partSize(), multipartConfiguration.diskLimit());
// Kicks off the encryption-upload pipeline;
// Note outputStream is automatically closed upon method completion.
_multipartPipeline.putLocalObject(requestBody, uploadId, outputStream);
// block till all part have been uploaded
for (Future<Map<Integer, UploadPartResponse>> future : observer.futures()) {
Map<Integer, UploadPartResponse> partResponseMap = future.get();
partResponseMap.forEach((partNumber, uploadPartResponse) -> partETags.add(CompletedPart.builder()
.partNumber(partNumber)
.eTag(uploadPartResponse.eTag())
.build()));
}
} catch (IOException | InterruptedException | ExecutionException | RuntimeException | Error ex) {
throw onAbort(observer, ex);
} finally {
if (defaultExecutorService) {
// shut down the locally created thread pool
es.shutdownNow();
}
// delete left-over temp files
outputStream.cleanup();
}
// Complete upload
return observer.onCompletion(partETags);
}
private <T extends Throwable> T onAbort(UploadObjectObserver observer, T t) {
observer.onAbort();
throw new S3EncryptionClientException(t.getMessage(), t);
}
/**
* See {@link S3Client#deleteObject(DeleteObjectRequest)}.
* <p>
* In the S3 Encryption Client, deleteObject also deletes the instruction file,
* if present.
* </p>
* @param deleteObjectRequest the request instance
* @return Result of the DeleteObject operation returned by the service.
*/
@Override
public DeleteObjectResponse deleteObject(DeleteObjectRequest deleteObjectRequest) throws AwsServiceException,
SdkClientException {
DeleteObjectRequest actualRequest = deleteObjectRequest.toBuilder()
.overrideConfiguration(API_NAME_INTERCEPTOR)
.build();
try {
// Delete the object
DeleteObjectResponse deleteObjectResponse = _wrappedAsyncClient.deleteObject(actualRequest).join();
// If Instruction file exists, delete the instruction file as well.
String instructionObjectKey = deleteObjectRequest.key() + INSTRUCTION_FILE_SUFFIX;
_wrappedAsyncClient.deleteObject(builder -> builder
.overrideConfiguration(API_NAME_INTERCEPTOR)
.bucket(deleteObjectRequest.bucket())
.key(instructionObjectKey)).join();
// Return original deletion
return deleteObjectResponse;
} catch (CompletionException e) {
throw new S3EncryptionClientException(e.getCause().getMessage(), e.getCause());
} catch (Exception e) {
throw new S3EncryptionClientException("Unable to delete object.", e);
}
}
/**
* See {@link S3Client#deleteObjects(DeleteObjectsRequest)}.
* <p>
* In the S3 Encryption Client, deleteObjects also deletes the instruction file(s),
* if present.
* </p>
* @param deleteObjectsRequest the request instance
* @return Result of the DeleteObjects operation returned by the service.
*/
@Override
public DeleteObjectsResponse deleteObjects(DeleteObjectsRequest deleteObjectsRequest) throws AwsServiceException,
SdkClientException {
DeleteObjectsRequest actualRequest = deleteObjectsRequest.toBuilder()
.overrideConfiguration(API_NAME_INTERCEPTOR)
.build();
try {
// Delete the objects
DeleteObjectsResponse deleteObjectsResponse = _wrappedAsyncClient.deleteObjects(actualRequest).join();
// If Instruction files exists, delete the instruction files as well.
List<ObjectIdentifier> deleteObjects = instructionFileKeysToDelete(deleteObjectsRequest);
_wrappedAsyncClient.deleteObjects(DeleteObjectsRequest.builder()
.overrideConfiguration(API_NAME_INTERCEPTOR)
.bucket(deleteObjectsRequest.bucket())
.delete(builder -> builder.objects(deleteObjects))
.build()).join();
return deleteObjectsResponse;
} catch (CompletionException e) {
throw new S3EncryptionClientException(e.getCause().getMessage(), e.getCause());
} catch (Exception e) {
throw new S3EncryptionClientException("Unable to delete objects.", e);
}
}
/**
* See {@link S3Client#createMultipartUpload(CreateMultipartUploadRequest)}
* <p>
* In the S3EncryptionClient, createMultipartUpload creates an encrypted
* multipart upload. Parts MUST be uploaded sequentially.
* See {@link S3EncryptionClient#uploadPart(UploadPartRequest, RequestBody)} for details.
* </p>
* @param request the request instance
* @return Result of the CreateMultipartUpload operation returned by the service.
*/
@Override
public CreateMultipartUploadResponse createMultipartUpload(CreateMultipartUploadRequest request) {
try {
return _multipartPipeline.createMultipartUpload(request);
} catch (CompletionException e) {
throw new S3EncryptionClientException(e.getCause().getMessage(), e.getCause());
} catch (Exception e) {
throw new S3EncryptionClientException("Unable to create Multipart upload.", e);
}
}
/**
* See {@link S3Client#uploadPart(UploadPartRequest, RequestBody)}
*
* <b>NOTE:</b> Because the encryption process requires context from block
* N-1 in order to encrypt block N, parts uploaded with the
* S3EncryptionClient (as opposed to the normal S3Client) must
* be uploaded serially, and in order. Otherwise, the previous encryption
* context isn't available to use when encrypting the current part.
* @param request the request instance
* @return Result of the UploadPart operation returned by the service.
*/
@Override
public UploadPartResponse uploadPart(UploadPartRequest request, RequestBody requestBody)
throws AwsServiceException, SdkClientException {
try {
return _multipartPipeline.uploadPart(request, requestBody);
} catch (CompletionException e) {
throw new S3EncryptionClientException(e.getCause().getMessage(), e.getCause());
} catch (Exception e) {
throw new S3EncryptionClientException("Unable to upload part.", e);
}
}
/**
* See {@link S3Client#completeMultipartUpload(CompleteMultipartUploadRequest)}
* @param request the request instance
* @return Result of the CompleteMultipartUpload operation returned by the service.
*/
@Override
public CompleteMultipartUploadResponse completeMultipartUpload(CompleteMultipartUploadRequest request)
throws AwsServiceException, SdkClientException {
try {
return _multipartPipeline.completeMultipartUpload(request);
} catch (CompletionException e) {
throw new S3EncryptionClientException(e.getCause().getMessage(), e.getCause());
} catch (Exception e) {
throw new S3EncryptionClientException("Unable to complete Multipart upload.", e);
}
}
/**
* See {@link S3Client#abortMultipartUpload(AbortMultipartUploadRequest)}
* @param request the request instance
* @return Result of the AbortMultipartUpload operation returned by the service.
*/
@Override
public AbortMultipartUploadResponse abortMultipartUpload(AbortMultipartUploadRequest request)
throws AwsServiceException, SdkClientException {
try {
return _multipartPipeline.abortMultipartUpload(request);
} catch (CompletionException e) {
throw new S3EncryptionClientException(e.getCause().getMessage(), e.getCause());
} catch (Exception e) {
throw new S3EncryptionClientException("Unable to abort Multipart upload.", e);
}
}
/**
* Closes the wrapped clients.
*/
@Override
public void close() {
_wrappedClient.close();
_wrappedAsyncClient.close();
}
// This is very similar to the S3EncryptionClient builder
// Make sure to keep both clients in mind when adding new builder options
public static class Builder {
// The non-encrypted APIs will use a default client.
private S3Client _wrappedClient;
private S3AsyncClient _wrappedAsyncClient;
private MultipartUploadObjectPipeline _multipartPipeline;
private CryptographicMaterialsManager _cryptoMaterialsManager;
private Keyring _keyring;
private SecretKey _aesKey;
private PartialRsaKeyPair _rsaKeyPair;
private String _kmsKeyId;
private boolean _enableLegacyWrappingAlgorithms = false;
private boolean _enableDelayedAuthenticationMode = false;
private boolean _enableMultipartPutObject = false;
private Provider _cryptoProvider = null;
private SecureRandom _secureRandom = new SecureRandom();
private boolean _enableLegacyUnauthenticatedModes = false;
private long _bufferSize = -1L;
private Builder() {
}
/**
* Sets the wrappedClient to be used for non-cryptographic operations.
*/
/*
* Note that this does NOT create a defensive clone of S3Client. Any modifications made to the wrapped
* S3Client will be reflected in this Builder.
*/
@SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "Pass mutability into wrapping client")
public Builder wrappedClient(S3Client _wrappedClient) {
if (_wrappedClient instanceof S3EncryptionClient) {
throw new S3EncryptionClientException("Cannot use S3EncryptionClient as wrapped client");
}
this._wrappedClient = _wrappedClient;
return this;
}
/**
* Sets the wrappedAsyncClient to be used for cryptographic operations.
*/
/*
* Note that this does NOT create a defensive clone of S3AsyncClient. Any modifications made to the wrapped
* S3AsyncClient will be reflected in this Builder.
*/
@SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "Pass mutability into wrapping client")
public Builder wrappedAsyncClient(S3AsyncClient _wrappedAsyncClient) {
if (_wrappedAsyncClient instanceof S3AsyncEncryptionClient) {
throw new S3EncryptionClientException("Cannot use S3AsyncEncryptionClient as wrapped client");
}
this._wrappedAsyncClient = _wrappedAsyncClient;
return this;
}
/**
* Specifies the {@link CryptographicMaterialsManager} to use for managing key wrapping keys.
* @param cryptoMaterialsManager the CMM to use
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder cryptoMaterialsManager(CryptographicMaterialsManager cryptoMaterialsManager) {
this._cryptoMaterialsManager = cryptoMaterialsManager;
checkKeyOptions();
return this;
}
/**
* Specifies the {@link Keyring} to use for key wrapping and unwrapping.
* @param keyring the Keyring instance to use
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder keyring(Keyring keyring) {
this._keyring = keyring;
checkKeyOptions();
return this;
}
/**
* Specifies a "raw" AES key to use for key wrapping/unwrapping.
* @param aesKey the AES key as a {@link SecretKey} instance
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder aesKey(SecretKey aesKey) {
this._aesKey = aesKey;
checkKeyOptions();
return this;
}
/**
* Specifies a "raw" RSA key pair to use for key wrapping/unwrapping.
* @param rsaKeyPair the RSA key pair as a {@link KeyPair} instance
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder rsaKeyPair(KeyPair rsaKeyPair) {
this._rsaKeyPair = new PartialRsaKeyPair(rsaKeyPair);
checkKeyOptions();
return this;
}
/**
* Specifies a "raw" RSA key pair to use for key wrapping/unwrapping.
* This option takes a {@link PartialRsaKeyPair} instance, which allows
* either a public key (decryption only) or private key (encryption only)
* rather than requiring both parts.
* @param partialRsaKeyPair the RSA key pair as a {@link PartialRsaKeyPair} instance
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder rsaKeyPair(PartialRsaKeyPair partialRsaKeyPair) {
this._rsaKeyPair = partialRsaKeyPair;
checkKeyOptions();
return this;
}
/**
* Specifies a KMS key to use for key wrapping/unwrapping. Any valid KMS key
* identifier (including the full ARN or an alias ARN) is permitted. When
* decrypting objects, the key referred to by this KMS key identifier is
* always used.
* @param kmsKeyId the KMS key identifier as a {@link String} instance
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder kmsKeyId(String kmsKeyId) {
this._kmsKeyId = kmsKeyId;
checkKeyOptions();
return this;
}
// We only want one way to use a key, if more than one is set, throw an error
private void checkKeyOptions() {
if (onlyOneNonNull(_cryptoMaterialsManager, _keyring, _aesKey, _rsaKeyPair, _kmsKeyId)) {
return;
}
throw new S3EncryptionClientException("Only one may be set of: crypto materials manager, keyring, AES key, RSA key pair, KMS key id");
}
private boolean onlyOneNonNull(Object... values) {
boolean haveOneNonNull = false;
for (Object o : values) {
if (o != null) {
if (haveOneNonNull) {
return false;
}
haveOneNonNull = true;
}
}
return haveOneNonNull;
}
/**
* When set to true, decryption of objects using legacy key wrapping
* modes is enabled.
* @param shouldEnableLegacyWrappingAlgorithms true to enable legacy wrapping algorithms
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder enableLegacyWrappingAlgorithms(boolean shouldEnableLegacyWrappingAlgorithms) {
this._enableLegacyWrappingAlgorithms = shouldEnableLegacyWrappingAlgorithms;
return this;
}
/**
* When set to true, decryption of content using legacy encryption algorithms
* is enabled. This includes use of GetObject requests with a range, as this
* mode is not authenticated.
* @param shouldEnableLegacyUnauthenticatedModes true to enable legacy content algorithms
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder enableLegacyUnauthenticatedModes(boolean shouldEnableLegacyUnauthenticatedModes) {
this._enableLegacyUnauthenticatedModes = shouldEnableLegacyUnauthenticatedModes;
return this;
}
/**
* When set to true, authentication of streamed objects is delayed until the
* entire object is read from the stream. When this mode is enabled, the consuming
* application must support a way to invalidate any data read from the stream as
* the tag will not be validated until the stream is read to completion, as the
* integrity of the data cannot be ensured. See the AWS Documentation for more
* information.
* @param shouldEnableDelayedAuthenticationMode true to enable delayed authentication
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder enableDelayedAuthenticationMode(boolean shouldEnableDelayedAuthenticationMode) {
this._enableDelayedAuthenticationMode = shouldEnableDelayedAuthenticationMode;
return this;
}
/**
* When set to true, the putObject method will use multipart upload to perform
* the upload. Disabled by default.
* @param _enableMultipartPutObject true enables the multipart upload implementation of putObject
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder enableMultipartPutObject(boolean _enableMultipartPutObject) {
this._enableMultipartPutObject = _enableMultipartPutObject;
return this;
}
/**
* Sets the buffer size for safe authentication used when delayed authentication mode is disabled.
* If buffer size is not given during client configuration, default buffer size is set to 64MiB.
* @param bufferSize the desired buffer size in Bytes.
* @return Returns a reference to this object so that method calls can be chained together.
* @throws S3EncryptionClientException if the specified buffer size is outside the allowed bounds
*/
public Builder setBufferSize(long bufferSize) {
if (bufferSize < MIN_ALLOWED_BUFFER_SIZE_BYTES || bufferSize > MAX_ALLOWED_BUFFER_SIZE_BYTES) {
throw new S3EncryptionClientException("Invalid buffer size: " + bufferSize + " Bytes. Buffer size must be between " + MIN_ALLOWED_BUFFER_SIZE_BYTES + " and " + MAX_ALLOWED_BUFFER_SIZE_BYTES + " Bytes.");
}
this._bufferSize = bufferSize;
return this;
}
/**
* Allows the user to pass an instance of {@link Provider} to be used
* for cryptographic operations. By default, the S3 Encryption Client
* will use the first compatible {@link Provider} in the chain. When this option
* is used, the given provider will be used for all cryptographic operations.
* If the provider is missing a required algorithm suite, e.g. AES-GCM, then
* operations may fail.
* Advanced option. Users who configure a {@link Provider} are responsible
* for the security and correctness of the provider.
* @param cryptoProvider the {@link Provider to always use}
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder cryptoProvider(Provider cryptoProvider) {
this._cryptoProvider = cryptoProvider;
return this;
}
/**
* Allows the user to pass an instance of {@link SecureRandom} to be used
* for generating keys and IVs. Advanced option. Users who provide a {@link SecureRandom}
* are responsible for the security and correctness of the {@link SecureRandom} implementation.
* @param secureRandom the {@link SecureRandom} instance to use
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder secureRandom(SecureRandom secureRandom) {
if (secureRandom == null) {
throw new S3EncryptionClientException("SecureRandom provided to S3EncryptionClient cannot be null");
}
_secureRandom = secureRandom;
return this;
}
/**
* Validates and builds the S3EncryptionClient according
* to the configuration options passed to the Builder object.
* @return an instance of the S3EncryptionClient
*/
public S3EncryptionClient build() {
if (!onlyOneNonNull(_cryptoMaterialsManager, _keyring, _aesKey, _rsaKeyPair, _kmsKeyId)) {
throw new S3EncryptionClientException("Exactly one must be set of: crypto materials manager, keyring, AES key, RSA key pair, KMS key id");
}
if (_bufferSize >= 0) {
if (_enableDelayedAuthenticationMode) {
throw new S3EncryptionClientException("Buffer size cannot be set when delayed authentication mode is enabled");
}
} else {
_bufferSize = DEFAULT_BUFFER_SIZE_BYTES;
}
if (_wrappedClient == null) {
_wrappedClient = S3Client.create();
}
if (_wrappedAsyncClient == null) {
_wrappedAsyncClient = S3AsyncClient.create();
}
if (_keyring == null) {
if (_aesKey != null) {
_keyring = AesKeyring.builder()
.wrappingKey(_aesKey)
.enableLegacyWrappingAlgorithms(_enableLegacyWrappingAlgorithms)
.secureRandom(_secureRandom)
.build();
} else if (_rsaKeyPair != null) {
_keyring = RsaKeyring.builder()
.wrappingKeyPair(_rsaKeyPair)
.enableLegacyWrappingAlgorithms(_enableLegacyWrappingAlgorithms)
.secureRandom(_secureRandom)
.build();
} else if (_kmsKeyId != null) {
_keyring = KmsKeyring.builder()
.wrappingKeyId(_kmsKeyId)
.enableLegacyWrappingAlgorithms(_enableLegacyWrappingAlgorithms)
.secureRandom(_secureRandom)
.build();
}
}
if (_cryptoMaterialsManager == null) {
_cryptoMaterialsManager = DefaultCryptoMaterialsManager.builder()
.keyring(_keyring)
.cryptoProvider(_cryptoProvider)
.build();
}
_multipartPipeline = MultipartUploadObjectPipeline.builder()
.s3AsyncClient(_wrappedAsyncClient)
.cryptoMaterialsManager(_cryptoMaterialsManager)
.secureRandom(_secureRandom)
.build();
return new S3EncryptionClient(this);
}
}
}
| 2,244 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/materials/DecryptDataKeyStrategy.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import java.security.GeneralSecurityException;
public interface DecryptDataKeyStrategy {
boolean isLegacy();
String keyProviderInfo();
byte[] decryptDataKey(DecryptionMaterials materials, byte[] encryptedDataKey)
throws GeneralSecurityException;
}
| 2,245 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/materials/DecryptMaterialsRequest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.encryption.s3.algorithms.AlgorithmSuite;
public class DecryptMaterialsRequest {
private final GetObjectRequest _s3Request;
private final AlgorithmSuite _algorithmSuite;
private final List<EncryptedDataKey> _encryptedDataKeys;
private final Map<String, String> _encryptionContext;
private final long _ciphertextLength;
private DecryptMaterialsRequest(Builder builder) {
this._s3Request = builder._s3Request;
this._algorithmSuite = builder._algorithmSuite;
this._encryptedDataKeys = builder._encryptedDataKeys;
this._encryptionContext = builder._encryptionContext;
this._ciphertextLength = builder._ciphertextLength;
}
static public Builder builder() {
return new Builder();
}
public GetObjectRequest s3Request() {
return _s3Request;
}
public AlgorithmSuite algorithmSuite() {
return _algorithmSuite;
}
/**
* Note that the underlying implementation uses a Collections.unmodifiableList which is
* immutable.
*/
@SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "False positive; underlying"
+ " implementation is immutable")
public List<EncryptedDataKey> encryptedDataKeys() {
return _encryptedDataKeys;
}
/**
* Note that the underlying implementation uses a Collections.unmodifiableMap which is
* immutable.
*/
@SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "False positive; underlying"
+ " implementation is immutable")
public Map<String, String> encryptionContext() {
return _encryptionContext;
}
public long ciphertextLength() {
return _ciphertextLength;
}
static public class Builder {
public GetObjectRequest _s3Request = null;
private AlgorithmSuite _algorithmSuite = AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF;
private Map<String, String> _encryptionContext = Collections.emptyMap();
private List<EncryptedDataKey> _encryptedDataKeys = Collections.emptyList();
private long _ciphertextLength = -1;
private Builder() {
}
public Builder s3Request(GetObjectRequest s3Request) {
_s3Request = s3Request;
return this;
}
public Builder algorithmSuite(AlgorithmSuite algorithmSuite) {
_algorithmSuite = algorithmSuite;
return this;
}
public Builder encryptionContext(Map<String, String> encryptionContext) {
_encryptionContext = encryptionContext == null
? Collections.emptyMap()
: Collections.unmodifiableMap(encryptionContext);
return this;
}
public Builder encryptedDataKeys(List<EncryptedDataKey> encryptedDataKeys) {
_encryptedDataKeys = encryptedDataKeys == null
? Collections.emptyList()
: Collections.unmodifiableList(encryptedDataKeys);
return this;
}
public Builder ciphertextLength(long ciphertextLength) {
_ciphertextLength = ciphertextLength;
return this;
}
public DecryptMaterialsRequest build() {
return new DecryptMaterialsRequest(this);
}
}
}
| 2,246 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/materials/AesKeyring.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import software.amazon.encryption.s3.S3EncryptionClientException;
import software.amazon.encryption.s3.algorithms.AlgorithmSuite;
import software.amazon.encryption.s3.internal.CryptoFactory;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
/**
* This keyring can wrap keys with the active keywrap algorithm and
* unwrap with the active and legacy algorithms for AES keys.
*/
public class AesKeyring extends S3Keyring {
private static final String KEY_ALGORITHM = "AES";
private final SecretKey _wrappingKey;
private final DecryptDataKeyStrategy _aesStrategy = new DecryptDataKeyStrategy() {
private static final String KEY_PROVIDER_INFO = "AES";
private static final String CIPHER_ALGORITHM = "AES";
@Override
public boolean isLegacy() {
return true;
}
@Override
public String keyProviderInfo() {
return KEY_PROVIDER_INFO;
}
@Override
public byte[] decryptDataKey(DecryptionMaterials materials, byte[] encryptedDataKey) throws GeneralSecurityException {
final Cipher cipher = CryptoFactory.createCipher(CIPHER_ALGORITHM, materials.cryptoProvider());
cipher.init(Cipher.DECRYPT_MODE, _wrappingKey);
return cipher.doFinal(encryptedDataKey);
}
};
private final DecryptDataKeyStrategy _aesWrapStrategy = new DecryptDataKeyStrategy() {
private static final String KEY_PROVIDER_INFO = "AESWrap";
private static final String CIPHER_ALGORITHM = "AESWrap";
@Override
public boolean isLegacy() {
return true;
}
@Override
public String keyProviderInfo() {
return KEY_PROVIDER_INFO;
}
@Override
public byte[] decryptDataKey(DecryptionMaterials materials, byte[] encryptedDataKey) throws GeneralSecurityException {
final Cipher cipher = CryptoFactory.createCipher(CIPHER_ALGORITHM, materials.cryptoProvider());
cipher.init(Cipher.UNWRAP_MODE, _wrappingKey);
Key plaintextKey = cipher.unwrap(encryptedDataKey, CIPHER_ALGORITHM, Cipher.SECRET_KEY);
return plaintextKey.getEncoded();
}
};
private final DataKeyStrategy _aesGcmStrategy = new DataKeyStrategy() {
private static final String KEY_PROVIDER_INFO = "AES/GCM";
private static final String CIPHER_ALGORITHM = "AES/GCM/NoPadding";
private static final int IV_LENGTH_BYTES = 12;
private static final int TAG_LENGTH_BYTES = 16;
private static final int TAG_LENGTH_BITS = TAG_LENGTH_BYTES * 8;
@Override
public boolean isLegacy() {
return false;
}
@Override
public String keyProviderInfo() {
return KEY_PROVIDER_INFO;
}
@Override
public EncryptionMaterials generateDataKey(EncryptionMaterials materials) {
return defaultGenerateDataKey(materials);
}
@Override
public EncryptionMaterials modifyMaterials(EncryptionMaterials materials) {
warnIfEncryptionContextIsPresent(materials);
return materials;
}
@Override
public byte[] encryptDataKey(SecureRandom secureRandom,
EncryptionMaterials materials)
throws GeneralSecurityException {
byte[] iv = new byte[IV_LENGTH_BYTES];
secureRandom.nextBytes(iv);
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(TAG_LENGTH_BITS, iv);
final Cipher cipher = CryptoFactory.createCipher(CIPHER_ALGORITHM, materials.cryptoProvider());
cipher.init(Cipher.ENCRYPT_MODE, _wrappingKey, gcmParameterSpec, secureRandom);
final byte[] aADBytes = AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF.cipherName().getBytes(StandardCharsets.UTF_8);
cipher.updateAAD(aADBytes);
byte[] ciphertext = cipher.doFinal(materials.plaintextDataKey());
// The encrypted data key is the iv prepended to the ciphertext
byte[] encodedBytes = new byte[iv.length + ciphertext.length];
System.arraycopy(iv, 0, encodedBytes, 0, iv.length);
System.arraycopy(ciphertext, 0, encodedBytes, iv.length, ciphertext.length);
return encodedBytes;
}
@Override
public byte[] decryptDataKey(DecryptionMaterials materials, byte[] encryptedDataKey) throws GeneralSecurityException {
byte[] iv = new byte[IV_LENGTH_BYTES];
byte[] ciphertext = new byte[encryptedDataKey.length - iv.length];
System.arraycopy(encryptedDataKey, 0, iv, 0, iv.length);
System.arraycopy(encryptedDataKey, iv.length, ciphertext, 0, ciphertext.length);
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(TAG_LENGTH_BITS, iv);
final Cipher cipher = CryptoFactory.createCipher(CIPHER_ALGORITHM, materials.cryptoProvider());
cipher.init(Cipher.DECRYPT_MODE, _wrappingKey, gcmParameterSpec);
final byte[] aADBytes = AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF.cipherName().getBytes(StandardCharsets.UTF_8);
cipher.updateAAD(aADBytes);
return cipher.doFinal(ciphertext);
}
};
private final Map<String, DecryptDataKeyStrategy> decryptDataKeyStrategies = new HashMap<>();
private AesKeyring(Builder builder) {
super(builder);
_wrappingKey = builder._wrappingKey;
decryptDataKeyStrategies.put(_aesStrategy.keyProviderInfo(), _aesStrategy);
decryptDataKeyStrategies.put(_aesWrapStrategy.keyProviderInfo(), _aesWrapStrategy);
decryptDataKeyStrategies.put(_aesGcmStrategy.keyProviderInfo(), _aesGcmStrategy);
}
public static Builder builder() {
return new Builder();
}
@Override
protected GenerateDataKeyStrategy generateDataKeyStrategy() {
return _aesGcmStrategy;
}
@Override
protected EncryptDataKeyStrategy encryptDataKeyStrategy() {
return _aesGcmStrategy;
}
@Override
protected Map<String, DecryptDataKeyStrategy> decryptDataKeyStrategies() {
return decryptDataKeyStrategies;
}
public static class Builder extends S3Keyring.Builder<AesKeyring, Builder> {
private SecretKey _wrappingKey;
private Builder() {
super();
}
@Override
protected Builder builder() {
return this;
}
public Builder wrappingKey(final SecretKey wrappingKey) {
if (wrappingKey == null) {
throw new S3EncryptionClientException("Wrapping key cannot be null!");
}
if (!wrappingKey.getAlgorithm().equals(KEY_ALGORITHM)) {
throw new S3EncryptionClientException("Invalid algorithm: " + wrappingKey.getAlgorithm() + ", expecting " + KEY_ALGORITHM);
}
_wrappingKey = wrappingKey;
return builder();
}
public AesKeyring build() {
return new AesKeyring(this);
}
}
}
| 2,247 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/materials/DataKeyGenerator.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import javax.crypto.SecretKey;
import software.amazon.encryption.s3.algorithms.AlgorithmSuite;
import java.security.Provider;
@FunctionalInterface
public interface DataKeyGenerator {
SecretKey generateDataKey(AlgorithmSuite algorithmSuite, Provider provider);
}
| 2,248 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/materials/PartialKeyPair.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import java.security.PrivateKey;
import java.security.PublicKey;
/**
* This interface allows use of key pairs where only one of the public or private keys
* has been provided. This allows consumers to be able to e.g. provide only the
* public portion of a key pair in the part of their application which puts encrypted
* objects into S3 to avoid distributing the private key.
*/
public interface PartialKeyPair {
PublicKey getPublicKey();
PrivateKey getPrivateKey();
}
| 2,249 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/materials/MultipartConfiguration.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import software.amazon.encryption.s3.internal.MultiFileOutputStream;
import software.amazon.encryption.s3.internal.UploadObjectObserver;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MultipartConfiguration {
private final long _partSize;
private final int _maxConnections;
private final long _diskLimit;
private final UploadObjectObserver _observer;
private final ExecutorService _es;
private final MultiFileOutputStream _outputStream;
public MultipartConfiguration(Builder builder) {
this._maxConnections = builder._maxConnections;
this._partSize = builder._partSize;
this._diskLimit = builder._diskLimit;
this._observer = builder._observer;
this._es = builder._es;
this._outputStream = builder._outputStream;
}
static public Builder builder() {
return new Builder();
}
public int maxConnections() {
return _maxConnections;
}
public long partSize() {
return _partSize;
}
public long diskLimit() {
return _diskLimit;
}
public MultiFileOutputStream multiFileOutputStream() {
return _outputStream;
}
public UploadObjectObserver uploadObjectObserver() {
return _observer;
}
public ExecutorService executorService() {
return _es;
}
static public class Builder {
private final long MIN_PART_SIZE = 5 << 20;
private MultiFileOutputStream _outputStream = new MultiFileOutputStream();
// Default Max Connections is 50
private int _maxConnections = 50;
// Set Min Allowed Part Size as Default
private long _partSize = MIN_PART_SIZE;
private long _diskLimit = Long.MAX_VALUE;
private UploadObjectObserver _observer = new UploadObjectObserver();
// If null, ExecutorService will be initialized in build() based on maxConnections.
private ExecutorService _es = null;
private Builder() {
}
public Builder maxConnections(int maxConnections) {
_maxConnections = maxConnections;
return this;
}
public Builder partSize(long partSize) {
if (partSize < MIN_PART_SIZE)
throw new IllegalArgumentException("partSize must be at least "
+ MIN_PART_SIZE);
_partSize = partSize;
return this;
}
public Builder diskLimit(long diskLimit) {
_diskLimit = diskLimit;
return this;
}
public Builder uploadObjectObserver(UploadObjectObserver observer) {
_observer = observer;
return this;
}
public Builder executorService(ExecutorService es) {
_es = es;
return this;
}
public Builder multiFileOutputStream(MultiFileOutputStream outputStream) {
_outputStream = outputStream;
return this;
}
public MultipartConfiguration build() {
if (_es == null) {
_es = Executors.newFixedThreadPool(_maxConnections);
}
return new MultipartConfiguration(this);
}
}
}
| 2,250 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/materials/S3Keyring.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import software.amazon.encryption.s3.S3EncryptionClient;
import software.amazon.encryption.s3.S3EncryptionClientException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.crypto.SecretKey;
import org.apache.commons.logging.LogFactory;
/**
* This serves as the base class for all the keyrings in the S3 encryption client.
* Shared functionality is all performed here.
*/
abstract public class S3Keyring implements Keyring {
public static final String KEY_PROVIDER_ID = "S3Keyring";
protected final DataKeyGenerator _dataKeyGenerator;
private final boolean _enableLegacyWrappingAlgorithms;
private final SecureRandom _secureRandom;
protected S3Keyring(Builder<?, ?> builder) {
_enableLegacyWrappingAlgorithms = builder._enableLegacyWrappingAlgorithms;
_secureRandom = builder._secureRandom;
_dataKeyGenerator = builder._dataKeyGenerator;
}
/**
* Generates a data key using the provided EncryptionMaterials and the configured DataKeyGenerator.
* <p>
* This method is intended for extension by customers who need to customize key generation within their Keyring
* implementation. It generates a data key for encryption using the algorithm suite and cryptographic provider
* configured in the provided EncryptionMaterials object.
*
* @param materials The EncryptionMaterials containing information about the algorithm suite and cryptographic
* provider to be used for data key generation.
* @return An updated EncryptionMaterials object with the generated plaintext data key.
*/
public EncryptionMaterials defaultGenerateDataKey(EncryptionMaterials materials) {
SecretKey dataKey = _dataKeyGenerator.generateDataKey(materials.algorithmSuite(), materials.cryptoProvider());
return materials.toBuilder()
.plaintextDataKey(dataKey.getEncoded())
.build();
}
@Override
public EncryptionMaterials onEncrypt(EncryptionMaterials materials) {
EncryptDataKeyStrategy encryptStrategy = encryptDataKeyStrategy();
// Allow encrypt strategy to modify the materials if necessary
materials = encryptStrategy.modifyMaterials(materials);
if (materials.plaintextDataKey() == null) {
materials = generateDataKeyStrategy().generateDataKey(materials);
}
// Return materials if they already have an encrypted data key.
if (!materials.encryptedDataKeys().isEmpty()) {
return materials;
}
try {
byte[] encryptedDataKeyCiphertext = encryptStrategy.encryptDataKey(_secureRandom, materials);
EncryptedDataKey encryptedDataKey = EncryptedDataKey.builder()
.keyProviderId(S3Keyring.KEY_PROVIDER_ID)
.keyProviderInfo(encryptStrategy.keyProviderInfo().getBytes(StandardCharsets.UTF_8))
.encryptedDataKey(encryptedDataKeyCiphertext)
.build();
List<EncryptedDataKey> encryptedDataKeys = new ArrayList<>(materials.encryptedDataKeys());
encryptedDataKeys.add(encryptedDataKey);
return materials.toBuilder()
.encryptedDataKeys(encryptedDataKeys)
.build();
} catch (Exception e) {
throw new S3EncryptionClientException("Unable to " + encryptStrategy.keyProviderInfo() + " wrap", e);
}
}
abstract protected GenerateDataKeyStrategy generateDataKeyStrategy();
abstract protected EncryptDataKeyStrategy encryptDataKeyStrategy();
@Override
public DecryptionMaterials onDecrypt(final DecryptionMaterials materials, List<EncryptedDataKey> encryptedDataKeys) {
if (materials.plaintextDataKey() != null) {
throw new S3EncryptionClientException("Decryption materials already contains a plaintext data key.");
}
if (encryptedDataKeys.size() != 1) {
throw new S3EncryptionClientException("Only one encrypted data key is supported, found: " + encryptedDataKeys.size());
}
EncryptedDataKey encryptedDataKey = encryptedDataKeys.get(0);
final String keyProviderId = encryptedDataKey.keyProviderId();
if (!KEY_PROVIDER_ID.equals(keyProviderId)) {
throw new S3EncryptionClientException("Unknown key provider: " + keyProviderId);
}
String keyProviderInfo = new String(encryptedDataKey.keyProviderInfo(), StandardCharsets.UTF_8);
DecryptDataKeyStrategy decryptStrategy = decryptDataKeyStrategies().get(keyProviderInfo);
if (decryptStrategy == null) {
throw new S3EncryptionClientException("The keyring does not support the object's key wrapping algorithm: " + keyProviderInfo);
}
if (decryptStrategy.isLegacy() && !_enableLegacyWrappingAlgorithms) {
throw new S3EncryptionClientException("Enable legacy wrapping algorithms to use legacy key wrapping algorithm: " + keyProviderInfo);
}
try {
byte[] plaintext = decryptStrategy.decryptDataKey(materials, encryptedDataKey.encryptedDatakey());
return materials.toBuilder().plaintextDataKey(plaintext).build();
} catch (GeneralSecurityException e) {
throw new S3EncryptionClientException("Unable to " + keyProviderInfo + " unwrap", e);
}
}
abstract protected Map<String, DecryptDataKeyStrategy> decryptDataKeyStrategies();
/**
* Checks if an encryption context is present in the EncryptionMaterials and issues a warning
* if an encryption context is found.
* <p>
* Encryption context is not recommended for use with
* non-KMS keyrings as it may not provide additional security benefits.
*
* @param materials EncryptionMaterials
*/
public void warnIfEncryptionContextIsPresent(EncryptionMaterials materials) {
materials.s3Request().overrideConfiguration()
.flatMap(overrideConfiguration ->
overrideConfiguration.executionAttributes()
.getOptionalAttribute(S3EncryptionClient.ENCRYPTION_CONTEXT))
.ifPresent(ctx -> LogFactory.getLog(getClass()).warn("Usage of Encryption Context provides no security benefit in " + getClass().getSimpleName()));
}
abstract public static class Builder<KeyringT extends S3Keyring, BuilderT extends Builder<KeyringT, BuilderT>> {
private boolean _enableLegacyWrappingAlgorithms = false;
private SecureRandom _secureRandom;
private DataKeyGenerator _dataKeyGenerator = new DefaultDataKeyGenerator();
protected Builder() {}
protected abstract BuilderT builder();
public BuilderT enableLegacyWrappingAlgorithms(boolean shouldEnableLegacyWrappingAlgorithms) {
this._enableLegacyWrappingAlgorithms = shouldEnableLegacyWrappingAlgorithms;
return builder();
}
/**
* Note that this does NOT create a defensive copy of the SecureRandom object. Any modifications to the
* object will be reflected in this Builder.
*/
@SuppressFBWarnings(value = "EI_EXPOSE_REP")
public BuilderT secureRandom(final SecureRandom secureRandom) {
if (secureRandom == null) {
throw new S3EncryptionClientException("SecureRandom provided to S3Keyring cannot be null");
}
_secureRandom = secureRandom;
return builder();
}
public BuilderT dataKeyGenerator(final DataKeyGenerator dataKeyGenerator) {
if (dataKeyGenerator == null) {
throw new S3EncryptionClientException("DataKeyGenerator cannot be null!");
}
_dataKeyGenerator = dataKeyGenerator;
return builder();
}
abstract public KeyringT build();
}
}
| 2,251 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/materials/EncryptDataKeyStrategy.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
public interface EncryptDataKeyStrategy {
String keyProviderInfo();
default EncryptionMaterials modifyMaterials(EncryptionMaterials materials) {
return materials;
}
byte[] encryptDataKey(
SecureRandom secureRandom,
EncryptionMaterials materials
) throws GeneralSecurityException;
} | 2,252 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/materials/EncryptionMaterials.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import software.amazon.awssdk.services.s3.model.S3Request;
import software.amazon.encryption.s3.algorithms.AlgorithmSuite;
import software.amazon.encryption.s3.internal.CipherMode;
import software.amazon.encryption.s3.internal.CipherProvider;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Provider;
import java.util.Collections;
import java.util.List;
import java.util.Map;
final public class EncryptionMaterials implements CryptographicMaterials {
// Original request
private final S3Request _s3Request;
// Identifies what sort of crypto algorithms we want to use
private final AlgorithmSuite _algorithmSuite;
// Additional information passed into encrypted that is required on decryption as well
// Should NOT contain sensitive information
private final Map<String, String> _encryptionContext;
private final List<EncryptedDataKey> _encryptedDataKeys;
private final byte[] _plaintextDataKey;
private final Provider _cryptoProvider;
private final long _plaintextLength;
private final long _ciphertextLength;
private EncryptionMaterials(Builder builder) {
this._s3Request = builder._s3Request;
this._algorithmSuite = builder._algorithmSuite;
this._encryptionContext = builder._encryptionContext;
this._encryptedDataKeys = builder._encryptedDataKeys;
this._plaintextDataKey = builder._plaintextDataKey;
this._cryptoProvider = builder._cryptoProvider;
this._plaintextLength = builder._plaintextLength;
this._ciphertextLength = _plaintextLength + _algorithmSuite.cipherTagLengthBytes();
}
static public Builder builder() {
return new Builder();
}
public S3Request s3Request() {
return _s3Request;
}
public AlgorithmSuite algorithmSuite() {
return _algorithmSuite;
}
/**
* Note that the underlying implementation uses a Collections.unmodifiableMap which is
* immutable.
*/
@Override
@SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "False positive; underlying"
+ " implementation is immutable")
public Map<String, String> encryptionContext() {
return _encryptionContext;
}
/**
* Note that the underlying implementation uses a Collections.unmodifiableList which is
* immutable.
*/
@SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "False positive; underlying"
+ " implementation is immutable")
public List<EncryptedDataKey> encryptedDataKeys() {
return _encryptedDataKeys;
}
public byte[] plaintextDataKey() {
if (_plaintextDataKey == null) {
return null;
}
return _plaintextDataKey.clone();
}
public long getPlaintextLength() {
return _plaintextLength;
}
public long getCiphertextLength() {
return _ciphertextLength;
}
public SecretKey dataKey() {
return new SecretKeySpec(_plaintextDataKey, algorithmSuite().dataKeyAlgorithm());
}
public Provider cryptoProvider() {
return _cryptoProvider;
}
@Override
public CipherMode cipherMode() {
return CipherMode.ENCRYPT;
}
@Override
public Cipher getCipher(byte[] iv) {
return CipherProvider.createAndInitCipher(this, iv);
}
public Builder toBuilder() {
return new Builder()
.s3Request(_s3Request)
.algorithmSuite(_algorithmSuite)
.encryptionContext(_encryptionContext)
.encryptedDataKeys(_encryptedDataKeys)
.plaintextDataKey(_plaintextDataKey)
.cryptoProvider(_cryptoProvider)
.plaintextLength(_plaintextLength);
}
static public class Builder {
private S3Request _s3Request = null;
private AlgorithmSuite _algorithmSuite = AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF;
private Map<String, String> _encryptionContext = Collections.emptyMap();
private List<EncryptedDataKey> _encryptedDataKeys = Collections.emptyList();
private byte[] _plaintextDataKey = null;
private long _plaintextLength = -1;
private Provider _cryptoProvider = null;
private Builder() {
}
public Builder s3Request(S3Request s3Request) {
_s3Request = s3Request;
return this;
}
public Builder algorithmSuite(AlgorithmSuite algorithmSuite) {
_algorithmSuite = algorithmSuite;
return this;
}
public Builder encryptionContext(Map<String, String> encryptionContext) {
_encryptionContext = encryptionContext == null
? Collections.emptyMap()
: Collections.unmodifiableMap(encryptionContext);
return this;
}
public Builder encryptedDataKeys(List<EncryptedDataKey> encryptedDataKeys) {
_encryptedDataKeys = encryptedDataKeys == null
? Collections.emptyList()
: Collections.unmodifiableList(encryptedDataKeys);
return this;
}
public Builder plaintextDataKey(byte[] plaintextDataKey) {
_plaintextDataKey = plaintextDataKey == null ? null : plaintextDataKey.clone();
return this;
}
public Builder cryptoProvider(Provider cryptoProvider) {
_cryptoProvider = cryptoProvider;
return this;
}
public Builder plaintextLength(long plaintextLength) {
_plaintextLength = plaintextLength;
return this;
}
public EncryptionMaterials build() {
return new EncryptionMaterials(this);
}
}
}
| 2,253 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/materials/DefaultCryptoMaterialsManager.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import software.amazon.encryption.s3.algorithms.AlgorithmSuite;
import java.security.Provider;
public class DefaultCryptoMaterialsManager implements CryptographicMaterialsManager {
private final Keyring _keyring;
private final Provider _cryptoProvider;
private DefaultCryptoMaterialsManager(Builder builder) {
_keyring = builder._keyring;
_cryptoProvider = builder._cryptoProvider;
}
public static Builder builder() {
return new Builder();
}
public EncryptionMaterials getEncryptionMaterials(EncryptionMaterialsRequest request) {
EncryptionMaterials materials = EncryptionMaterials.builder()
.s3Request(request.s3Request())
.algorithmSuite(AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF)
.encryptionContext(request.encryptionContext())
.cryptoProvider(_cryptoProvider)
.plaintextLength(request.plaintextLength())
.build();
return _keyring.onEncrypt(materials);
}
public DecryptionMaterials decryptMaterials(DecryptMaterialsRequest request) {
DecryptionMaterials materials = DecryptionMaterials.builder()
.s3Request(request.s3Request())
.algorithmSuite(request.algorithmSuite())
.encryptionContext(request.encryptionContext())
.ciphertextLength(request.ciphertextLength())
.cryptoProvider(_cryptoProvider)
.build();
return _keyring.onDecrypt(materials, request.encryptedDataKeys());
}
public static class Builder {
private Keyring _keyring;
private Provider _cryptoProvider;
private Builder() {}
public Builder keyring(Keyring keyring) {
this._keyring = keyring;
return this;
}
public Builder cryptoProvider(Provider cryptoProvider) {
this._cryptoProvider = cryptoProvider;
return this;
}
public DefaultCryptoMaterialsManager build() {
return new DefaultCryptoMaterialsManager(this);
}
}
}
| 2,254 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/materials/CryptographicMaterialsManager.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
public interface CryptographicMaterialsManager {
EncryptionMaterials getEncryptionMaterials(EncryptionMaterialsRequest request);
DecryptionMaterials decryptMaterials(DecryptMaterialsRequest request);
}
| 2,255 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/materials/GenerateDataKeyStrategy.java | package software.amazon.encryption.s3.materials;
public interface GenerateDataKeyStrategy {
String keyProviderInfo();
EncryptionMaterials generateDataKey(EncryptionMaterials materials);
}
| 2,256 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/materials/DataKeyStrategy.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
public abstract class DataKeyStrategy implements GenerateDataKeyStrategy, EncryptDataKeyStrategy, DecryptDataKeyStrategy {
}
| 2,257 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/materials/EncryptionMaterialsRequest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.Collections;
import java.util.Map;
import software.amazon.awssdk.services.s3.model.S3Request;
final public class EncryptionMaterialsRequest {
private final S3Request _s3Request;
private final Map<String, String> _encryptionContext;
private final long _plaintextLength;
private EncryptionMaterialsRequest(Builder builder) {
this._s3Request = builder._s3Request;
this._encryptionContext = builder._encryptionContext;
this._plaintextLength = builder._plaintextLength;
}
static public Builder builder() {
return new Builder();
}
public S3Request s3Request() {
return _s3Request;
}
public long plaintextLength() {
return _plaintextLength;
}
/**
* Note that the underlying implementation uses a Collections.unmodifiableMap which is
* immutable.
*/
@SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "False positive; underlying"
+ " implementation is immutable")
public Map<String, String> encryptionContext() {
return _encryptionContext;
}
static public class Builder {
public S3Request _s3Request = null;
private Map<String, String> _encryptionContext = Collections.emptyMap();
private long _plaintextLength = -1;
private Builder() {
}
public Builder s3Request(S3Request s3Request) {
_s3Request = s3Request;
return this;
}
public Builder encryptionContext(Map<String, String> encryptionContext) {
_encryptionContext = encryptionContext == null
? Collections.emptyMap()
: Collections.unmodifiableMap(encryptionContext);
return this;
}
public Builder plaintextLength(final long plaintextLength) {
_plaintextLength = plaintextLength;
return this;
}
public EncryptionMaterialsRequest build() {
return new EncryptionMaterialsRequest(this);
}
}
}
| 2,258 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/materials/KmsKeyring.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.core.ApiName;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.kms.KmsClient;
import software.amazon.awssdk.services.kms.model.DataKeySpec;
import software.amazon.awssdk.services.kms.model.DecryptRequest;
import software.amazon.awssdk.services.kms.model.DecryptResponse;
import software.amazon.awssdk.services.kms.model.EncryptRequest;
import software.amazon.awssdk.services.kms.model.EncryptResponse;
import software.amazon.awssdk.services.kms.model.GenerateDataKeyRequest;
import software.amazon.awssdk.services.kms.model.GenerateDataKeyResponse;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Request;
import software.amazon.encryption.s3.S3EncryptionClient;
import software.amazon.encryption.s3.S3EncryptionClientException;
import software.amazon.encryption.s3.internal.ApiNameVersion;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
/**
* This keyring can wrap keys with the active keywrap algorithm and
* unwrap with the active and legacy algorithms for KMS keys.
*/
public class KmsKeyring extends S3Keyring {
private static final ApiName API_NAME = ApiNameVersion.apiNameWithVersion();
private static final String KEY_ID_CONTEXT_KEY = "kms_cmk_id";
private final KmsClient _kmsClient;
private final String _wrappingKeyId;
private final DecryptDataKeyStrategy _kmsStrategy = new DecryptDataKeyStrategy() {
private static final String KEY_PROVIDER_INFO = "kms";
@Override
public boolean isLegacy() {
return true;
}
@Override
public String keyProviderInfo() {
return KEY_PROVIDER_INFO;
}
@Override
public byte[] decryptDataKey(DecryptionMaterials materials, byte[] encryptedDataKey) {
DecryptRequest request = DecryptRequest.builder()
.keyId(_wrappingKeyId)
.encryptionContext(materials.encryptionContext())
.ciphertextBlob(SdkBytes.fromByteArray(encryptedDataKey))
.overrideConfiguration(builder -> builder.addApiName(API_NAME))
.build();
DecryptResponse response = _kmsClient.decrypt(request);
return response.plaintext().asByteArray();
}
};
private final DataKeyStrategy _kmsContextStrategy = new DataKeyStrategy() {
private static final String KEY_PROVIDER_INFO = "kms+context";
private static final String ENCRYPTION_CONTEXT_ALGORITHM_KEY = "aws:x-amz-cek-alg";
@Override
public boolean isLegacy() {
return false;
}
@Override
public String keyProviderInfo() {
return KEY_PROVIDER_INFO;
}
@Override
public EncryptionMaterials modifyMaterials(EncryptionMaterials materials) {
S3Request s3Request = materials.s3Request();
Map<String, String> encryptionContext = new HashMap<>(materials.encryptionContext());
if (s3Request.overrideConfiguration().isPresent()) {
AwsRequestOverrideConfiguration overrideConfig = s3Request.overrideConfiguration().get();
Optional<Map<String, String>> optEncryptionContext = overrideConfig
.executionAttributes()
.getOptionalAttribute(S3EncryptionClient.ENCRYPTION_CONTEXT);
optEncryptionContext.ifPresent(encryptionContext::putAll);
}
if (encryptionContext.containsKey(ENCRYPTION_CONTEXT_ALGORITHM_KEY)) {
throw new S3EncryptionClientException(ENCRYPTION_CONTEXT_ALGORITHM_KEY + " is a reserved key for the S3 encryption client");
}
encryptionContext.put(ENCRYPTION_CONTEXT_ALGORITHM_KEY, materials.algorithmSuite().cipherName());
return materials.toBuilder()
.encryptionContext(encryptionContext)
.build();
}
@Override
public EncryptionMaterials generateDataKey(EncryptionMaterials materials) {
DataKeySpec dataKeySpec;
if (!materials.algorithmSuite().dataKeyAlgorithm().equals("AES")) {
throw new S3EncryptionClientException(String.format("The data key algorithm %s is not supported by AWS " + "KMS", materials.algorithmSuite().dataKeyAlgorithm()));
}
switch (materials.algorithmSuite().dataKeyLengthBits()) {
case 128:
dataKeySpec = DataKeySpec.AES_128;
break;
case 256:
dataKeySpec = DataKeySpec.AES_256;
break;
default:
throw new S3EncryptionClientException(String.format("The data key length %d is not supported by " + "AWS KMS", materials.algorithmSuite().dataKeyLengthBits()));
}
GenerateDataKeyRequest request = GenerateDataKeyRequest.builder()
.keyId(_wrappingKeyId)
.keySpec(dataKeySpec)
.encryptionContext(materials.encryptionContext())
.overrideConfiguration(builder -> builder.addApiName(API_NAME))
.build();
GenerateDataKeyResponse response = _kmsClient.generateDataKey(request);
byte[] encryptedDataKeyCiphertext = response.ciphertextBlob().asByteArray();
EncryptedDataKey encryptedDataKey = EncryptedDataKey.builder()
.keyProviderId(S3Keyring.KEY_PROVIDER_ID)
.keyProviderInfo(keyProviderInfo().getBytes(StandardCharsets.UTF_8))
.encryptedDataKey(Objects.requireNonNull(encryptedDataKeyCiphertext))
.build();
List<EncryptedDataKey> encryptedDataKeys = new ArrayList<>(materials.encryptedDataKeys());
encryptedDataKeys.add(encryptedDataKey);
return materials.toBuilder()
.encryptedDataKeys(encryptedDataKeys)
.plaintextDataKey(response.plaintext().asByteArray())
.build();
}
@Override
public byte[] encryptDataKey(SecureRandom secureRandom, EncryptionMaterials materials) {
HashMap<String, String> encryptionContext = new HashMap<>(materials.encryptionContext());
EncryptRequest request = EncryptRequest.builder()
.keyId(_wrappingKeyId)
.encryptionContext(encryptionContext)
.plaintext(SdkBytes.fromByteArray(materials.plaintextDataKey()))
.overrideConfiguration(builder -> builder.addApiName(API_NAME))
.build();
EncryptResponse response = _kmsClient.encrypt(request);
return response.ciphertextBlob().asByteArray();
}
@Override
public byte[] decryptDataKey(DecryptionMaterials materials, byte[] encryptedDataKey) {
Map<String, String> requestEncryptionContext = new HashMap<>();
GetObjectRequest s3Request = materials.s3Request();
if (s3Request.overrideConfiguration().isPresent()) {
AwsRequestOverrideConfiguration overrideConfig = s3Request.overrideConfiguration().get();
Optional<Map<String, String>> optEncryptionContext = overrideConfig
.executionAttributes()
.getOptionalAttribute(S3EncryptionClient.ENCRYPTION_CONTEXT);
if (optEncryptionContext.isPresent()) {
requestEncryptionContext = new HashMap<>(optEncryptionContext.get());
}
}
// We are validating the encryption context to match S3EC V2 behavior
Map<String, String> materialsEncryptionContextCopy = new HashMap<>(materials.encryptionContext());
materialsEncryptionContextCopy.remove(KEY_ID_CONTEXT_KEY);
materialsEncryptionContextCopy.remove(ENCRYPTION_CONTEXT_ALGORITHM_KEY);
if (!materialsEncryptionContextCopy.equals(requestEncryptionContext)) {
throw new S3EncryptionClientException("Provided encryption context does not match information retrieved from S3");
}
DecryptRequest request = DecryptRequest.builder()
.keyId(_wrappingKeyId)
.encryptionContext(materials.encryptionContext())
.ciphertextBlob(SdkBytes.fromByteArray(encryptedDataKey))
.overrideConfiguration(builder -> builder.addApiName(API_NAME))
.build();
DecryptResponse response = _kmsClient.decrypt(request);
return response.plaintext().asByteArray();
}
};
private final Map<String, DecryptDataKeyStrategy> decryptDataKeyStrategies = new HashMap<>();
public KmsKeyring(Builder builder) {
super(builder);
_kmsClient = builder._kmsClient;
_wrappingKeyId = builder._wrappingKeyId;
decryptDataKeyStrategies.put(_kmsStrategy.keyProviderInfo(), _kmsStrategy);
decryptDataKeyStrategies.put(_kmsContextStrategy.keyProviderInfo(), _kmsContextStrategy);
}
public static Builder builder() {
return new Builder();
}
@Override
protected GenerateDataKeyStrategy generateDataKeyStrategy() {
return _kmsContextStrategy;
}
@Override
protected EncryptDataKeyStrategy encryptDataKeyStrategy() {
return _kmsContextStrategy;
}
@Override
protected Map<String, DecryptDataKeyStrategy> decryptDataKeyStrategies() {
return decryptDataKeyStrategies;
}
public static class Builder extends S3Keyring.Builder<KmsKeyring, Builder> {
private KmsClient _kmsClient = KmsClient.builder().build();
private String _wrappingKeyId;
private Builder() {
super();
}
@Override
protected Builder builder() {
return this;
}
/**
* Note that this does NOT create a defensive clone of KmsClient. Any modifications made to the wrapped
* client will be reflected in this Builder.
*/
@SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "Pass mutability into wrapping client")
public Builder kmsClient(KmsClient kmsClient) {
_kmsClient = kmsClient;
return this;
}
public Builder wrappingKeyId(String wrappingKeyId) {
_wrappingKeyId = wrappingKeyId;
return this;
}
public KmsKeyring build() {
return new KmsKeyring(this);
}
}
}
| 2,259 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/materials/DecryptionMaterials.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.encryption.s3.algorithms.AlgorithmSuite;
import software.amazon.encryption.s3.internal.CipherMode;
import software.amazon.encryption.s3.internal.CipherProvider;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Provider;
import java.util.Collections;
import java.util.Map;
final public class DecryptionMaterials implements CryptographicMaterials {
// Original request
private final GetObjectRequest _s3Request;
// Identifies what sort of crypto algorithms we want to use
private final AlgorithmSuite _algorithmSuite;
// Additional information passed into encrypted that is required on decryption as well
// Should NOT contain sensitive information
private final Map<String, String> _encryptionContext;
private final byte[] _plaintextDataKey;
private long _ciphertextLength;
private Provider _cryptoProvider;
private DecryptionMaterials(Builder builder) {
this._s3Request = builder._s3Request;
this._algorithmSuite = builder._algorithmSuite;
this._encryptionContext = builder._encryptionContext;
this._plaintextDataKey = builder._plaintextDataKey;
this._ciphertextLength = builder._ciphertextLength;
this._cryptoProvider = builder._cryptoProvider;
}
static public Builder builder() {
return new Builder();
}
public GetObjectRequest s3Request() {
return _s3Request;
}
public AlgorithmSuite algorithmSuite() {
return _algorithmSuite;
}
/**
* Note that the underlying implementation uses a Collections.unmodifiableMap which is
* immutable.
*/
@SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "False positive; underlying"
+ " implementation is immutable")
public Map<String, String> encryptionContext() {
return _encryptionContext;
}
public byte[] plaintextDataKey() {
if (_plaintextDataKey == null) {
return null;
}
return _plaintextDataKey.clone();
}
public SecretKey dataKey() {
return new SecretKeySpec(_plaintextDataKey, algorithmSuite().dataKeyAlgorithm());
}
public Provider cryptoProvider() {
return _cryptoProvider;
}
public long ciphertextLength() {
return _ciphertextLength;
}
@Override
public CipherMode cipherMode() {
return CipherMode.DECRYPT;
}
@Override
public Cipher getCipher(byte[] iv) {
return CipherProvider.createAndInitCipher(this, iv);
}
public Builder toBuilder() {
return new Builder()
.s3Request(_s3Request)
.algorithmSuite(_algorithmSuite)
.encryptionContext(_encryptionContext)
.plaintextDataKey(_plaintextDataKey)
.ciphertextLength(_ciphertextLength)
.cryptoProvider(_cryptoProvider);
}
static public class Builder {
public GetObjectRequest _s3Request = null;
private Provider _cryptoProvider = null;
private AlgorithmSuite _algorithmSuite = AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF;
private Map<String, String> _encryptionContext = Collections.emptyMap();
private byte[] _plaintextDataKey = null;
private long _ciphertextLength = -1;
private Builder() {
}
public Builder s3Request(GetObjectRequest s3Request) {
_s3Request = s3Request;
return this;
}
public Builder algorithmSuite(AlgorithmSuite algorithmSuite) {
_algorithmSuite = algorithmSuite;
return this;
}
public Builder encryptionContext(Map<String, String> encryptionContext) {
_encryptionContext = encryptionContext == null
? Collections.emptyMap()
: Collections.unmodifiableMap(encryptionContext);
return this;
}
public Builder plaintextDataKey(byte[] plaintextDataKey) {
_plaintextDataKey = plaintextDataKey == null ? null : plaintextDataKey.clone();
return this;
}
public Builder ciphertextLength(long ciphertextLength) {
_ciphertextLength = ciphertextLength;
return this;
}
public Builder cryptoProvider(Provider cryptoProvider) {
_cryptoProvider = cryptoProvider;
return this;
}
public DecryptionMaterials build() {
return new DecryptionMaterials(this);
}
}
}
| 2,260 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/materials/EncryptedDataKey.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
public class EncryptedDataKey {
// forms the "domain" of the key e.g. "aws-kms"
private final String _keyProviderId;
// a unique identifer e.g. an ARN
private final byte[] _keyProviderInfo;
// Encrypted data key ciphertext
private final byte[] _encryptedDataKey;
private EncryptedDataKey(Builder builder) {
this._keyProviderId = builder._keyProviderId;
this._keyProviderInfo = builder._keyProviderInfo;
this._encryptedDataKey = builder._encryptedDataKey;
}
static public Builder builder() {
return new Builder();
}
public String keyProviderId() {
return _keyProviderId;
}
public byte[] keyProviderInfo() {
if (_keyProviderInfo == null) {
return null;
}
return _keyProviderInfo.clone();
}
public byte[] encryptedDatakey() {
if (_encryptedDataKey == null) {
return null;
}
return _encryptedDataKey.clone();
}
static public class Builder {
private String _keyProviderId = null;
private byte[] _keyProviderInfo = null;
private byte[] _encryptedDataKey = null;
private Builder() {
}
public Builder keyProviderId(String keyProviderId) {
_keyProviderId = keyProviderId;
return this;
}
public Builder keyProviderInfo(byte[] keyProviderInfo) {
_keyProviderInfo = keyProviderInfo == null ? null : keyProviderInfo.clone();
return this;
}
public Builder encryptedDataKey(byte[] encryptedDataKey) {
_encryptedDataKey = encryptedDataKey == null ? null : encryptedDataKey.clone();
return this;
}
public EncryptedDataKey build() {
return new EncryptedDataKey(this);
}
}
}
| 2,261 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/materials/RsaKeyring.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import software.amazon.encryption.s3.S3EncryptionClientException;
import software.amazon.encryption.s3.internal.CryptoFactory;
import javax.crypto.Cipher;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource.PSpecified;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.SecureRandom;
import java.security.spec.MGF1ParameterSpec;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* This keyring can wrap keys with the active keywrap algorithm and
* unwrap with the active and legacy algorithms for RSA keys.
*/
public class RsaKeyring extends S3Keyring {
private final PartialRsaKeyPair _partialRsaKeyPair;
// Used exclusively by v1's EncryptionOnly mode
private final DecryptDataKeyStrategy _rsaStrategy = new DecryptDataKeyStrategy() {
private static final String KEY_PROVIDER_INFO = "RSA";
private static final String CIPHER_ALGORITHM = "RSA";
@Override
public boolean isLegacy() {
return true;
}
@Override
public String keyProviderInfo() {
return KEY_PROVIDER_INFO;
}
@Override
public byte[] decryptDataKey(DecryptionMaterials materials, byte[] encryptedDataKey) throws GeneralSecurityException {
final Cipher cipher = CryptoFactory.createCipher(CIPHER_ALGORITHM, materials.cryptoProvider());
cipher.init(Cipher.DECRYPT_MODE, _partialRsaKeyPair.getPrivateKey());
return cipher.doFinal(encryptedDataKey);
}
};
private final DecryptDataKeyStrategy _rsaEcbStrategy = new DecryptDataKeyStrategy() {
private static final String KEY_PROVIDER_INFO = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";
private static final String CIPHER_ALGORITHM = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";
@Override
public boolean isLegacy() {
return true;
}
@Override
public String keyProviderInfo() {
return KEY_PROVIDER_INFO;
}
@Override
public byte[] decryptDataKey(DecryptionMaterials materials, byte[] encryptedDataKey) throws GeneralSecurityException {
final Cipher cipher = CryptoFactory.createCipher(CIPHER_ALGORITHM, materials.cryptoProvider());
cipher.init(Cipher.UNWRAP_MODE, _partialRsaKeyPair.getPrivateKey());
Key plaintextKey = cipher.unwrap(encryptedDataKey, CIPHER_ALGORITHM, Cipher.SECRET_KEY);
return plaintextKey.getEncoded();
}
};
private final DataKeyStrategy _rsaOaepStrategy = new DataKeyStrategy() {
private static final String KEY_PROVIDER_INFO = "RSA-OAEP-SHA1";
private static final String CIPHER_ALGORITHM = "RSA/ECB/OAEPPadding";
private static final String DIGEST_NAME = "SHA-1";
private static final String MGF_NAME = "MGF1";
// Java 8 doesn't support static class fields in inner classes
private final MGF1ParameterSpec MGF_PARAMETER_SPEC = new MGF1ParameterSpec(DIGEST_NAME);
private final OAEPParameterSpec OAEP_PARAMETER_SPEC =
new OAEPParameterSpec(DIGEST_NAME, MGF_NAME, MGF_PARAMETER_SPEC, PSpecified.DEFAULT);
@Override
public boolean isLegacy() {
return false;
}
@Override
public String keyProviderInfo() {
return KEY_PROVIDER_INFO;
}
@Override
public EncryptionMaterials generateDataKey(EncryptionMaterials materials) {
return defaultGenerateDataKey(materials);
}
@Override
public EncryptionMaterials modifyMaterials(EncryptionMaterials materials) {
warnIfEncryptionContextIsPresent(materials);
return materials;
}
@Override
public byte[] encryptDataKey(SecureRandom secureRandom,
EncryptionMaterials materials) throws GeneralSecurityException {
final Cipher cipher = CryptoFactory.createCipher(CIPHER_ALGORITHM, materials.cryptoProvider());
cipher.init(Cipher.WRAP_MODE, _partialRsaKeyPair.getPublicKey(), OAEP_PARAMETER_SPEC, secureRandom);
// Create a pseudo-data key with the content encryption appended to the data key
byte[] dataKey = materials.plaintextDataKey();
byte[] dataCipherName = materials.algorithmSuite().cipherName().getBytes(
StandardCharsets.UTF_8);
byte[] pseudoDataKey = new byte[1 + dataKey.length + dataCipherName.length];
pseudoDataKey[0] = (byte)dataKey.length;
System.arraycopy(dataKey, 0, pseudoDataKey, 1, dataKey.length);
System.arraycopy(dataCipherName, 0, pseudoDataKey, 1 + dataKey.length, dataCipherName.length);
byte[] ciphertext = cipher.wrap(new SecretKeySpec(pseudoDataKey, materials.algorithmSuite().dataKeyAlgorithm()));
return ciphertext;
}
@Override
public byte[] decryptDataKey(DecryptionMaterials materials, byte[] encryptedDataKey) throws GeneralSecurityException {
final Cipher cipher = CryptoFactory.createCipher(CIPHER_ALGORITHM, materials.cryptoProvider());
cipher.init(Cipher.UNWRAP_MODE, _partialRsaKeyPair.getPrivateKey(), OAEP_PARAMETER_SPEC);
String dataKeyAlgorithm = materials.algorithmSuite().dataKeyAlgorithm();
Key pseudoDataKey = cipher.unwrap(encryptedDataKey, dataKeyAlgorithm, Cipher.SECRET_KEY);
return parsePseudoDataKey(materials, pseudoDataKey.getEncoded());
}
private byte[] parsePseudoDataKey(DecryptionMaterials materials, byte[] pseudoDataKey) {
int dataKeyLengthBytes = pseudoDataKey[0];
if (!(dataKeyLengthBytes == 16 || dataKeyLengthBytes == 24 || dataKeyLengthBytes == 32)) {
throw new S3EncryptionClientException("Invalid key length (" + dataKeyLengthBytes + ") in encrypted data key");
}
int dataCipherNameLength = pseudoDataKey.length - dataKeyLengthBytes - 1;
if (dataCipherNameLength <= 0) {
throw new S3EncryptionClientException("Invalid data cipher name length (" + dataCipherNameLength + ") in encrypted data key");
}
byte[] dataKey = new byte[dataKeyLengthBytes];
byte[] dataCipherName = new byte[dataCipherNameLength];
System.arraycopy(pseudoDataKey, 1, dataKey, 0, dataKeyLengthBytes);
System.arraycopy(pseudoDataKey, 1 + dataKeyLengthBytes, dataCipherName, 0, dataCipherNameLength);
byte[] expectedDataCipherName = materials.algorithmSuite().cipherName().getBytes(StandardCharsets.UTF_8);
if (!Arrays.equals(expectedDataCipherName, dataCipherName)) {
throw new S3EncryptionClientException("The data cipher does not match the data cipher used for encryption. The object may be altered or corrupted");
}
return dataKey;
}
};
private final Map<String, DecryptDataKeyStrategy> decryptDataKeyStrategies = new HashMap<>();
private RsaKeyring(Builder builder) {
super(builder);
_partialRsaKeyPair = builder._partialRsaKeyPair;
decryptDataKeyStrategies.put(_rsaStrategy.keyProviderInfo(), _rsaStrategy);
decryptDataKeyStrategies.put(_rsaEcbStrategy.keyProviderInfo(), _rsaEcbStrategy);
decryptDataKeyStrategies.put(_rsaOaepStrategy.keyProviderInfo(), _rsaOaepStrategy);
}
public static Builder builder() {
return new Builder();
}
@Override
protected GenerateDataKeyStrategy generateDataKeyStrategy() {
return _rsaOaepStrategy;
}
@Override
protected EncryptDataKeyStrategy encryptDataKeyStrategy() {
return _rsaOaepStrategy;
}
@Override
protected Map<String, DecryptDataKeyStrategy> decryptDataKeyStrategies() {
return decryptDataKeyStrategies;
}
public static class Builder extends S3Keyring.Builder<S3Keyring, Builder> {
private PartialRsaKeyPair _partialRsaKeyPair;
private Builder() {
super();
}
@Override
protected Builder builder() {
return this;
}
public Builder wrappingKeyPair(final PartialRsaKeyPair partialRsaKeyPair) {
_partialRsaKeyPair = partialRsaKeyPair;
return builder();
}
public RsaKeyring build() {
return new RsaKeyring(this);
}
}
}
| 2,262 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/materials/DefaultDataKeyGenerator.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import software.amazon.encryption.s3.algorithms.AlgorithmSuite;
import software.amazon.encryption.s3.internal.CryptoFactory;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.Provider;
public class DefaultDataKeyGenerator implements DataKeyGenerator {
public SecretKey generateDataKey(AlgorithmSuite algorithmSuite, Provider provider) {
KeyGenerator generator = CryptoFactory.generateKey(algorithmSuite.dataKeyAlgorithm(), provider);
generator.init(algorithmSuite.dataKeyLengthBits());
return generator.generateKey();
}
}
| 2,263 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/materials/Keyring.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import java.util.List;
/**
* Keyring defines the interface for wrapping data keys. A {@link CryptographicMaterialsManager} will use
* keyrings to encrypt and decrypt data keys.
*/
public interface Keyring {
EncryptionMaterials onEncrypt(final EncryptionMaterials materials);
DecryptionMaterials onDecrypt(final DecryptionMaterials materials, final List<EncryptedDataKey> encryptedDataKeys);
}
| 2,264 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/materials/PartialRsaKeyPair.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import software.amazon.encryption.s3.S3EncryptionClientException;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Objects;
public class PartialRsaKeyPair implements PartialKeyPair {
private final PrivateKey _privateKey;
private final PublicKey _publicKey;
private static final String RSA_KEY_ALGORITHM = "RSA";
public PartialRsaKeyPair(final KeyPair keyPair) {
_privateKey = keyPair.getPrivate();
_publicKey = keyPair.getPublic();
validateKeyPair();
}
public PartialRsaKeyPair(final PrivateKey privateKey, final PublicKey publicKey) {
_privateKey = privateKey;
_publicKey = publicKey;
validateKeyPair();
}
private void validateKeyPair() {
if (_privateKey == null && _publicKey == null) {
throw new S3EncryptionClientException("The public key and private cannot both be null. You must provide a " +
"public key, or a private key, or both.");
}
if (_privateKey != null && !_privateKey.getAlgorithm().equals(RSA_KEY_ALGORITHM)) {
throw new S3EncryptionClientException("%s is not a supported algorithm. Only RSA keys are supported. Please reconfigure your client with an RSA key.");
}
if (_publicKey != null && !_publicKey.getAlgorithm().equals(RSA_KEY_ALGORITHM)) {
throw new S3EncryptionClientException("%s is not a supported algorithm. Only RSA keys are supported. Please reconfigure your client with an RSA key.");
}
}
@Override
public PublicKey getPublicKey() {
if (_publicKey == null) {
throw new S3EncryptionClientException("No public key provided. You must configure a public key to be able to" +
" encrypt data.");
}
return _publicKey;
}
@Override
public PrivateKey getPrivateKey() {
if (_privateKey == null) {
throw new S3EncryptionClientException("No private key provided. You must configure a private key to be able to" +
" decrypt data.");
}
return _privateKey;
}
public static Builder builder() {
return new Builder();
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
PartialRsaKeyPair that = (PartialRsaKeyPair) o;
return Objects.equals(_privateKey, that._privateKey) && Objects.equals(_publicKey, that._publicKey);
}
@Override
public int hashCode() {
return Objects.hash(_privateKey, _publicKey);
}
public static class Builder {
private PublicKey _publicKey;
private PrivateKey _privateKey;
private Builder() {}
public Builder publicKey(final PublicKey publicKey) {
_publicKey = publicKey;
return this;
}
public Builder privateKey(final PrivateKey privateKey) {
_privateKey = privateKey;
return this;
}
public PartialRsaKeyPair build() {
return new PartialRsaKeyPair(_privateKey, _publicKey);
}
}
}
| 2,265 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/materials/CryptographicMaterials.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.materials;
import software.amazon.awssdk.services.s3.model.S3Request;
import software.amazon.encryption.s3.algorithms.AlgorithmSuite;
import software.amazon.encryption.s3.internal.CipherMode;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import java.security.Provider;
import java.util.Map;
public interface CryptographicMaterials {
AlgorithmSuite algorithmSuite();
S3Request s3Request();
Map<String, String> encryptionContext();
SecretKey dataKey();
Provider cryptoProvider();
CipherMode cipherMode();
Cipher getCipher(byte[] iv);
}
| 2,266 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/algorithms/AlgorithmSuite.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.algorithms;
public enum AlgorithmSuite {
ALG_AES_256_GCM_IV12_TAG16_NO_KDF(0x0072,
false,
"AES",
256,
"AES/GCM/NoPadding",
128,
96,
128,
AlgorithmConstants.GCM_MAX_CONTENT_LENGTH_BITS),
ALG_AES_256_CTR_IV16_TAG16_NO_KDF(0x0071,
true,
"AES",
256,
"AES/CTR/NoPadding",
128,
128,
128,
AlgorithmConstants.CTR_MAX_CONTENT_LENGTH_BYTES),
ALG_AES_256_CBC_IV16_NO_KDF(0x0070,
true,
"AES",
256,
"AES/CBC/PKCS5Padding",
128,
128,
0,
AlgorithmConstants.CBC_MAX_CONTENT_LENGTH_BYTES);
private final int _id;
private final boolean _isLegacy;
private final String _dataKeyAlgorithm;
private final int _dataKeyLengthBits;
private final String _cipherName;
private final int _cipherBlockSizeBits;
private final int _cipherIvLengthBits;
private final int _cipherTagLengthBits;
private final long _cipherMaxContentLengthBits;
AlgorithmSuite(int id,
boolean isLegacy,
String dataKeyAlgorithm,
int dataKeyLengthBits,
String cipherName,
int cipherBlockSizeBits,
int cipherIvLengthBits,
int cipherTagLengthBits,
long cipherMaxContentLengthBits
) {
this._id = id;
this._isLegacy = isLegacy;
this._dataKeyAlgorithm = dataKeyAlgorithm;
this._dataKeyLengthBits = dataKeyLengthBits;
this._cipherName = cipherName;
this._cipherBlockSizeBits = cipherBlockSizeBits;
this._cipherIvLengthBits = cipherIvLengthBits;
this._cipherTagLengthBits = cipherTagLengthBits;
this._cipherMaxContentLengthBits = cipherMaxContentLengthBits;
}
public int id() {
return _id;
}
public boolean isLegacy() {
return _isLegacy;
}
public String dataKeyAlgorithm() {
return _dataKeyAlgorithm;
}
public int dataKeyLengthBits() {
return _dataKeyLengthBits;
}
public String cipherName() {
return _cipherName;
}
public int cipherTagLengthBits() {
return _cipherTagLengthBits;
}
public int cipherTagLengthBytes() {
return _cipherTagLengthBits / 8;
}
public int iVLengthBytes() {
return _cipherIvLengthBits / 8;
}
public int cipherBlockSizeBytes() {
return _cipherBlockSizeBits / 8;
}
public long cipherMaxContentLengthBits() {
return _cipherMaxContentLengthBits;
}
public long cipherMaxContentLengthBytes() {
return _cipherMaxContentLengthBits / 8;
}
}
| 2,267 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/algorithms/AlgorithmConstants.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.algorithms;
class AlgorithmConstants {
/**
* The maximum number of 16-byte blocks that can be encrypted with a
* GCM cipher. Note the maximum bit-length of the plaintext is (2^39 - 256),
* which translates to a maximum byte-length of (2^36 - 32), which in turn
* translates to a maximum block-length of (2^32 - 2).
* <p>
* Reference: <a href="http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf">
* NIST Special Publication 800-38D.</a>.
*/
static final long GCM_MAX_CONTENT_LENGTH_BITS = (1L << 39) - 256;
/**
* The Maximum length of the content that can be encrypted in CBC mode.
*/
static final long CBC_MAX_CONTENT_LENGTH_BYTES = (1L << 55);
/**
* The maximum number of bytes that can be securely encrypted per a single key using AES/CTR.
*/
static final long CTR_MAX_CONTENT_LENGTH_BYTES = -1;
}
| 2,268 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/UploadObjectObserver.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import org.apache.commons.logging.LogFactory;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.CompletedPart;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.SdkPartType;
import software.amazon.awssdk.services.s3.model.UploadPartRequest;
import software.amazon.awssdk.services.s3.model.UploadPartResponse;
import software.amazon.encryption.s3.S3EncryptionClient;
import software.amazon.encryption.s3.S3EncryptionClientException;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
public class UploadObjectObserver {
private final List<Future<Map<Integer, UploadPartResponse>>> futures = new ArrayList<>();
private PutObjectRequest request;
private String uploadId;
private S3AsyncClient s3AsyncClient;
private S3EncryptionClient s3EncryptionClient;
private ExecutorService es;
public UploadObjectObserver init(PutObjectRequest req,
S3AsyncClient s3AsyncClient, S3EncryptionClient s3EncryptionClient, ExecutorService es) {
this.request = req;
this.s3AsyncClient = s3AsyncClient;
this.s3EncryptionClient = s3EncryptionClient;
this.es = es;
return this;
}
protected CreateMultipartUploadRequest newCreateMultipartUploadRequest(
PutObjectRequest request) {
return CreateMultipartUploadRequest.builder()
.bucket(request.bucket())
.key(request.key())
.metadata(request.metadata())
.overrideConfiguration(request.overrideConfiguration().orElse(null))
.build();
}
public String onUploadCreation(PutObjectRequest req) {
CreateMultipartUploadResponse res =
s3EncryptionClient.createMultipartUpload(newCreateMultipartUploadRequest(req));
return this.uploadId = res.uploadId();
}
public void onPartCreate(PartCreationEvent event) {
final File part = event.getPart();
final UploadPartRequest reqUploadPart =
newUploadPartRequest(event);
final OnFileDelete fileDeleteObserver = event.getFileDeleteObserver();
futures.add(es.submit(new Callable<Map<Integer, UploadPartResponse>>() {
@Override
public Map<Integer, UploadPartResponse> call() {
// Upload the ciphertext directly via the non-encrypting
// s3 client
try {
AsyncRequestBody noRetriesBody = new NoRetriesAsyncRequestBody(AsyncRequestBody.fromFile(part));
return uploadPart(reqUploadPart, noRetriesBody);
} catch (CompletionException e) {
// Unwrap completion exception
throw new S3EncryptionClientException(e.getCause().getMessage(), e.getCause());
} finally {
// clean up part already uploaded
if (!part.delete()) {
LogFactory.getLog(getClass()).debug(
"Ignoring failure to delete file " + part
+ " which has already been uploaded");
} else {
if (fileDeleteObserver != null)
fileDeleteObserver.onFileDelete(null);
}
}
}
}));
}
public CompleteMultipartUploadResponse onCompletion(List<CompletedPart> partETags) {
return s3EncryptionClient.completeMultipartUpload(builder -> builder
.bucket(request.bucket())
.key(request.key())
.uploadId(uploadId)
.multipartUpload(partBuilder -> partBuilder.parts(partETags)));
}
public void onAbort() {
for (Future<?> future : futures()) {
future.cancel(true);
}
if (uploadId != null) {
try {
s3EncryptionClient.abortMultipartUpload(builder -> builder.bucket(request.bucket())
.key(request.key())
.uploadId(uploadId));
} catch (Exception e) {
LogFactory.getLog(getClass())
.debug("Failed to abort multi-part upload: " + uploadId, e);
}
}
}
protected UploadPartRequest newUploadPartRequest(PartCreationEvent event) {
final SdkPartType partType;
if (event.isLastPart()) {
partType = SdkPartType.LAST;
} else {
partType = SdkPartType.DEFAULT;
}
return UploadPartRequest.builder()
.bucket(request.bucket())
.key(request.key())
.partNumber(event.getPartNumber())
.sdkPartType(partType)
.uploadId(uploadId)
.build();
}
protected Map<Integer, UploadPartResponse> uploadPart(UploadPartRequest reqUploadPart, AsyncRequestBody requestBody) {
// Upload the ciphertext directly via the non-encrypting
// s3 client
return Collections.singletonMap(reqUploadPart.partNumber(), s3AsyncClient.uploadPart(reqUploadPart, requestBody).join());
}
public List<Future<Map<Integer, UploadPartResponse>>> futures() {
return futures;
}
} | 2,269 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/BufferedCipherSubscriber.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.utils.BinaryUtils;
import software.amazon.encryption.s3.S3EncryptionClientException;
import software.amazon.encryption.s3.S3EncryptionClientSecurityException;
import software.amazon.encryption.s3.materials.CryptographicMaterials;
import javax.crypto.Cipher;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A subscriber which decrypts data by buffering the object's contents
* so that authentication can be done before any plaintext is released.
* This prevents "release of unauthenticated plaintext" at the cost of
* allocating a large buffer.
*/
public class BufferedCipherSubscriber implements Subscriber<ByteBuffer> {
private final AtomicInteger contentRead = new AtomicInteger(0);
private final AtomicBoolean doneFinal = new AtomicBoolean(false);
private final Subscriber<? super ByteBuffer> wrappedSubscriber;
private final int contentLength;
private Cipher cipher;
private final CryptographicMaterials materials;
private final byte[] iv;
private byte[] outputBuffer;
private final Queue<ByteBuffer> buffers = new ConcurrentLinkedQueue<>();
BufferedCipherSubscriber(Subscriber<? super ByteBuffer> wrappedSubscriber, Long contentLength, CryptographicMaterials materials, byte[] iv, long bufferSizeInBytes) {
this.wrappedSubscriber = wrappedSubscriber;
if (contentLength == null) {
throw new S3EncryptionClientException("contentLength cannot be null in buffered mode. To enable unbounded " +
"streaming, reconfigure the S3 Encryption Client with Delayed Authentication mode enabled.");
}
if (contentLength > bufferSizeInBytes) {
throw new S3EncryptionClientException(String.format("The object you are attempting to decrypt exceeds the maximum buffer size: " + bufferSizeInBytes +
" for the default (buffered) mode. Either increase your buffer size when configuring your client, " +
"or enable Delayed Authentication mode to disable buffered decryption."));
}
this.contentLength = Math.toIntExact(contentLength);
this.materials = materials;
this.iv = iv;
cipher = materials.getCipher(iv);
}
@Override
public void onSubscribe(Subscription s) {
wrappedSubscriber.onSubscribe(s);
}
@Override
public void onNext(ByteBuffer byteBuffer) {
int amountToReadFromByteBuffer = getAmountToReadFromByteBuffer(byteBuffer);
if (amountToReadFromByteBuffer > 0) {
byte[] buf = BinaryUtils.copyBytesFrom(byteBuffer, amountToReadFromByteBuffer);
try {
outputBuffer = cipher.update(buf, 0, amountToReadFromByteBuffer);
} catch (final IllegalStateException exception) {
// This happens when the stream is reset and the cipher is reused with the
// same key/IV. It's actually fine here, because the data is the same, but any
// sane implementation will throw an exception.
// Request a new cipher using the same materials to avoid reinit issues
cipher = CipherProvider.createAndInitCipher(materials, iv);
}
if (outputBuffer == null && amountToReadFromByteBuffer < cipher.getBlockSize()) {
// The underlying data is too short to fill in the block cipher
// This is true at the end of the file, so complete to get the final
// bytes
this.onComplete();
}
// Enqueue the buffer until all data is read
buffers.add(ByteBuffer.wrap(outputBuffer));
// Sometimes, onComplete won't be called, so we check if all
// data is read to avoid hanging indefinitely
if (contentRead.get() == contentLength) {
this.onComplete();
}
// This avoids the subscriber waiting indefinitely for more data
// without actually releasing any plaintext before it can be authenticated
wrappedSubscriber.onNext(ByteBuffer.allocate(0));
}
}
private int getAmountToReadFromByteBuffer(ByteBuffer byteBuffer) {
long amountReadSoFar = contentRead.getAndAdd(byteBuffer.remaining());
long amountRemaining = Math.max(0, contentLength - amountReadSoFar);
if (amountRemaining > byteBuffer.remaining()) {
return byteBuffer.remaining();
} else {
return Math.toIntExact(amountRemaining);
}
}
@Override
public void onError(Throwable t) {
wrappedSubscriber.onError(t);
}
@Override
public void onComplete() {
if (doneFinal.get()) {
// doFinal has already been called, bail out
return;
}
try {
outputBuffer = cipher.doFinal();
doneFinal.set(true);
// Once doFinal is called, then we can release the plaintext
if (contentRead.get() == contentLength) {
while (!buffers.isEmpty()) {
wrappedSubscriber.onNext(buffers.remove());
}
}
// Send the final bytes to the wrapped subscriber
wrappedSubscriber.onNext(ByteBuffer.wrap(outputBuffer));
} catch (final GeneralSecurityException exception) {
// Forward error, else the wrapped subscriber waits indefinitely
wrappedSubscriber.onError(exception);
throw new S3EncryptionClientSecurityException(exception.getMessage(), exception);
}
wrappedSubscriber.onComplete();
}
}
| 2,270 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/MultipartEncryptedContent.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import javax.crypto.Cipher;
public class MultipartEncryptedContent extends EncryptedContent {
private final Cipher _cipher;
public MultipartEncryptedContent(byte[] iv, Cipher cipher, long ciphertextLength) {
super(iv, null, ciphertextLength);
_cipher = cipher;
_iv = iv;
}
/**
* MultipartEncryptedContent cannot store a ciphertext AsyncRequestBody
* as it one is generated for each part using the cipher in this class.
* @throws UnsupportedOperationException always
*/
@Override
public AsyncRequestBody getAsyncCiphertext() {
throw new UnsupportedOperationException("MultipartEncryptedContent does not support async ciphertext!");
}
/**
* @return the cipher used for the duration of the multipart upload
*/
public Cipher getCipher() {
return _cipher;
}
}
| 2,271 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/MetadataKeyConstants.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
public class MetadataKeyConstants {
public static final String ENCRYPTED_DATA_KEY_V1 = "x-amz-key";
public static final String ENCRYPTED_DATA_KEY_V2 = "x-amz-key-v2";
// This is the name of the keyring/algorithm e.g. AES/GCM or kms+context
public static final String ENCRYPTED_DATA_KEY_ALGORITHM = "x-amz-wrap-alg";
public static final String ENCRYPTED_DATA_KEY_CONTEXT = "x-amz-matdesc";
public static final String CONTENT_IV = "x-amz-iv";
// This is usually an actual Java cipher e.g. AES/GCM/NoPadding
public static final String CONTENT_CIPHER = "x-amz-cek-alg";
public static final String CONTENT_CIPHER_TAG_LENGTH = "x-amz-tag-len";
}
| 2,272 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/CipherMode.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import javax.crypto.Cipher;
/**
* A wrapper around Cipher.opMode which models multipart encryption
* as distinct from "ordinary" encryption.
*/
public enum CipherMode {
ENCRYPT(Cipher.ENCRYPT_MODE),
DECRYPT(Cipher.DECRYPT_MODE),
MULTIPART_ENCRYPT(Cipher.ENCRYPT_MODE);
private final int _opMode;
CipherMode(final int opMode) {
_opMode = opMode;
}
public int opMode() {
return _opMode;
}
}
| 2,273 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/PartCreationEvent.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import java.io.File;
public class PartCreationEvent {
private final File part;
private final int partNumber;
private final boolean isLastPart;
private final OnFileDelete fileDeleteObserver;
PartCreationEvent(File part, int partNumber, boolean isLastPart,
OnFileDelete fileDeleteObserver) {
if (part == null) {
throw new IllegalArgumentException("part must not be specified");
}
this.part = part;
this.partNumber = partNumber;
this.isLastPart = isLastPart;
this.fileDeleteObserver = fileDeleteObserver;
}
/**
* Returns a non-null part (in the form of a file) for multipart upload.
*/
public File getPart() {
return part;
}
public int getPartNumber() {
return partNumber;
}
public boolean isLastPart() {
return isLastPart;
}
/**
* Returns an observer for file deletion; or null if there is none.
*/
public OnFileDelete getFileDeleteObserver() {
return fileDeleteObserver;
}
}
| 2,274 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/ContentDecryptionStrategy.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import software.amazon.encryption.s3.materials.DecryptionMaterials;
import java.io.InputStream;
@FunctionalInterface
public interface ContentDecryptionStrategy {
InputStream decryptContent(ContentMetadata contentMetadata, DecryptionMaterials materials, InputStream ciphertext);
}
| 2,275 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/EncryptedContent.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import software.amazon.awssdk.core.async.AsyncRequestBody;
public class EncryptedContent {
private AsyncRequestBody _encryptedRequestBody;
private long _ciphertextLength = -1;
protected byte[] _iv;
public EncryptedContent(final byte[] iv, final AsyncRequestBody encryptedRequestBody, final long ciphertextLength) {
_iv = iv;
_encryptedRequestBody = encryptedRequestBody;
_ciphertextLength = ciphertextLength;
}
public byte[] getIv() {
return _iv;
}
public long getCiphertextLength() {
return _ciphertextLength;
}
public AsyncRequestBody getAsyncCiphertext() {
return _encryptedRequestBody;
}
}
| 2,276 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/CipherPublisher.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.encryption.s3.legacy.internal.RangedGetUtils;
import software.amazon.encryption.s3.materials.CryptographicMaterials;
import java.nio.ByteBuffer;
/**
* A Publisher which encrypts and decrypts data as it passes through
* using a configured Cipher instance.
*/
public class CipherPublisher implements SdkPublisher<ByteBuffer> {
private final SdkPublisher<ByteBuffer> wrappedPublisher;
private final CryptographicMaterials materials;
private final Long contentLength;
private final long[] range;
private final String contentRange;
private final int cipherTagLengthBits;
private final byte[] iv;
public CipherPublisher(final SdkPublisher<ByteBuffer> wrappedPublisher, final Long contentLength, long[] range,
String contentRange, int cipherTagLengthBits, final CryptographicMaterials materials, final byte[] iv) {
this.wrappedPublisher = wrappedPublisher;
this.materials = materials;
this.contentLength = contentLength;
this.range = range;
this.contentRange = contentRange;
this.cipherTagLengthBits = cipherTagLengthBits;
this.iv = iv;
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> subscriber) {
// Wrap the (customer) subscriber in a CipherSubscriber, then subscribe it
// to the wrapped (ciphertext) publisher
Subscriber<? super ByteBuffer> wrappedSubscriber = RangedGetUtils.adjustToDesiredRange(subscriber, range, contentRange, cipherTagLengthBits);
wrappedPublisher.subscribe(new CipherSubscriber(wrappedSubscriber, contentLength, materials, iv));
}
}
| 2,277 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/PutEncryptedObjectPipeline.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.encryption.s3.S3EncryptionClientException;
import software.amazon.encryption.s3.algorithms.AlgorithmSuite;
import software.amazon.encryption.s3.materials.CryptographicMaterialsManager;
import software.amazon.encryption.s3.materials.EncryptionMaterials;
import software.amazon.encryption.s3.materials.EncryptionMaterialsRequest;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import static software.amazon.encryption.s3.internal.ApiNameVersion.API_NAME_INTERCEPTOR;
public class PutEncryptedObjectPipeline {
final private S3AsyncClient _s3AsyncClient;
final private CryptographicMaterialsManager _cryptoMaterialsManager;
final private AsyncContentEncryptionStrategy _asyncContentEncryptionStrategy;
final private ContentMetadataEncodingStrategy _contentMetadataEncodingStrategy;
public static Builder builder() {
return new Builder();
}
private PutEncryptedObjectPipeline(Builder builder) {
this._s3AsyncClient = builder._s3AsyncClient;
this._cryptoMaterialsManager = builder._cryptoMaterialsManager;
this._asyncContentEncryptionStrategy = builder._asyncContentEncryptionStrategy;
this._contentMetadataEncodingStrategy = builder._contentMetadataEncodingStrategy;
}
public CompletableFuture<PutObjectResponse> putObject(PutObjectRequest request, AsyncRequestBody requestBody) {
final Long contentLength;
if (request.contentLength() != null) {
if (requestBody.contentLength().isPresent() && !request.contentLength().equals(requestBody.contentLength().get())) {
// if the contentLength values do not match, throw an exception, since we don't know which is correct
throw new S3EncryptionClientException("The contentLength provided in the request object MUST match the " +
"contentLength in the request body");
} else if (!requestBody.contentLength().isPresent()) {
// no contentLength in request body, use the one in request
contentLength = request.contentLength();
} else {
// only remaining case is when the values match, so either works here
contentLength = request.contentLength();
}
} else {
contentLength = requestBody.contentLength().orElse(-1L);
}
if (contentLength > AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF.cipherMaxContentLengthBytes()) {
throw new S3EncryptionClientException("The contentLength of the object you are attempting to encrypt exceeds" +
"the maximum length allowed for GCM encryption.");
}
EncryptionMaterialsRequest encryptionMaterialsRequest = EncryptionMaterialsRequest.builder()
.s3Request(request)
.plaintextLength(contentLength)
.build();
EncryptionMaterials materials = _cryptoMaterialsManager.getEncryptionMaterials(encryptionMaterialsRequest);
EncryptedContent encryptedContent = _asyncContentEncryptionStrategy.encryptContent(materials, requestBody);
Map<String, String> metadata = new HashMap<>(request.metadata());
metadata = _contentMetadataEncodingStrategy.encodeMetadata(materials, encryptedContent.getIv(), metadata);
PutObjectRequest encryptedPutRequest = request.toBuilder()
.overrideConfiguration(API_NAME_INTERCEPTOR)
.contentLength(encryptedContent.getCiphertextLength())
.metadata(metadata)
.build();
return _s3AsyncClient.putObject(encryptedPutRequest, encryptedContent.getAsyncCiphertext());
}
public static class Builder {
private S3AsyncClient _s3AsyncClient;
private CryptographicMaterialsManager _cryptoMaterialsManager;
private SecureRandom _secureRandom;
private AsyncContentEncryptionStrategy _asyncContentEncryptionStrategy;
private final ContentMetadataEncodingStrategy _contentMetadataEncodingStrategy = ContentMetadataStrategy.OBJECT_METADATA;
private Builder() {
}
/**
* Note that this does NOT create a defensive clone of S3Client. Any modifications made to the wrapped
* S3Client will be reflected in this Builder.
*/
@SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "Pass mutability into wrapping client")
public Builder s3AsyncClient(S3AsyncClient s3AsyncClient) {
this._s3AsyncClient = s3AsyncClient;
return this;
}
public Builder cryptoMaterialsManager(CryptographicMaterialsManager cryptoMaterialsManager) {
this._cryptoMaterialsManager = cryptoMaterialsManager;
return this;
}
public Builder secureRandom(SecureRandom secureRandom) {
this._secureRandom = secureRandom;
return this;
}
public PutEncryptedObjectPipeline build() {
// Default to AesGcm since it is the only active (non-legacy) content encryption strategy
if (_asyncContentEncryptionStrategy == null) {
_asyncContentEncryptionStrategy = StreamingAesGcmContentStrategy
.builder()
.secureRandom(_secureRandom)
.build();
}
return new PutEncryptedObjectPipeline(this);
}
}
}
| 2,278 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/MultipartContentEncryptionStrategy.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import software.amazon.encryption.s3.materials.EncryptionMaterials;
@FunctionalInterface
public interface MultipartContentEncryptionStrategy {
MultipartEncryptedContent initMultipartEncryption(EncryptionMaterials materials);
}
| 2,279 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/ContentMetadataEncodingStrategy.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import software.amazon.encryption.s3.materials.EncryptionMaterials;
import java.util.Map;
@FunctionalInterface
public interface ContentMetadataEncodingStrategy {
Map<String, String> encodeMetadata(EncryptionMaterials materials, byte[] iv,
Map<String, String> metadata);
}
| 2,280 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/StreamingAesGcmContentStrategy.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.encryption.s3.S3EncryptionClientException;
import software.amazon.encryption.s3.algorithms.AlgorithmSuite;
import software.amazon.encryption.s3.materials.EncryptionMaterials;
import javax.crypto.Cipher;
import java.security.SecureRandom;
public class StreamingAesGcmContentStrategy implements AsyncContentEncryptionStrategy, MultipartContentEncryptionStrategy {
final private SecureRandom _secureRandom;
private StreamingAesGcmContentStrategy(Builder builder) {
this._secureRandom = builder._secureRandom;
}
public static Builder builder() {
return new Builder();
}
@Override
public MultipartEncryptedContent initMultipartEncryption(EncryptionMaterials materials) {
if (materials.getPlaintextLength() > AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF.cipherMaxContentLengthBytes()) {
throw new S3EncryptionClientException("The contentLength of the object you are attempting to encrypt exceeds" +
"the maximum length allowed for GCM encryption.");
}
final byte[] iv = new byte[materials.algorithmSuite().iVLengthBytes()];
_secureRandom.nextBytes(iv);
final Cipher cipher = CipherProvider.createAndInitCipher(materials, iv);
return new MultipartEncryptedContent(iv, cipher, materials.getCiphertextLength());
}
@Override
public EncryptedContent encryptContent(EncryptionMaterials materials, AsyncRequestBody content) {
if (materials.getPlaintextLength() > AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF.cipherMaxContentLengthBytes()) {
throw new S3EncryptionClientException("The contentLength of the object you are attempting to encrypt exceeds" +
"the maximum length allowed for GCM encryption.");
}
final byte[] iv = new byte[materials.algorithmSuite().iVLengthBytes()];
_secureRandom.nextBytes(iv);
AsyncRequestBody encryptedAsyncRequestBody = new CipherAsyncRequestBody(content, materials.getCiphertextLength(), materials, iv);
return new EncryptedContent(iv, encryptedAsyncRequestBody, materials.getCiphertextLength());
}
public static class Builder {
private SecureRandom _secureRandom = new SecureRandom();
private Builder() {
}
/**
* Note that this does NOT create a defensive copy of the SecureRandom object. Any modifications to the
* object will be reflected in this Builder.
*/
@SuppressFBWarnings(value = "EI_EXPOSE_REP")
public Builder secureRandom(SecureRandom secureRandom) {
if (secureRandom == null) {
throw new S3EncryptionClientException("SecureRandom provided to StreamingAesGcmContentStrategy cannot be null");
}
_secureRandom = secureRandom;
return this;
}
public StreamingAesGcmContentStrategy build() {
return new StreamingAesGcmContentStrategy(this);
}
}
}
| 2,281 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/CipherInputStream.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import software.amazon.awssdk.core.io.SdkFilterInputStream;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import java.io.IOException;
import java.io.InputStream;
/**
* A cipher stream for encrypting or decrypting data using an unauthenticated block cipher.
*/
public class CipherInputStream extends SdkFilterInputStream {
private static final int MAX_RETRY_COUNT = 1000;
private static final int DEFAULT_IN_BUFFER_SIZE = 512;
protected final Cipher cipher;
protected boolean eofReached;
protected byte[] inputBuffer;
protected byte[] outputBuffer;
protected int currentPosition;
protected int maxPosition;
public CipherInputStream(InputStream inputStream, Cipher cipher) {
super(inputStream);
this.cipher = cipher;
this.inputBuffer = new byte[DEFAULT_IN_BUFFER_SIZE];
}
@Override
public int read() throws IOException {
if (!readNextChunk()) {
return -1;
}
// Cast the last byte to int with a value between 0-255, masking out the
// higher bits. In other words, this is abs(x % 256).
return ((int) outputBuffer[currentPosition++] & 0xFF);
}
@Override
public int read(byte buffer[]) throws IOException {
return read(buffer, 0, buffer.length);
}
@Override
public int read(byte buffer[], int off, int targetLength) throws IOException {
if (!readNextChunk()) {
return -1;
}
if (targetLength <= 0) {
return 0;
}
int length = maxPosition - currentPosition;
if (targetLength < length) {
length = targetLength;
}
System.arraycopy(outputBuffer, currentPosition, buffer, off, length);
currentPosition += length;
return length;
}
private boolean readNextChunk() throws IOException {
if (currentPosition >= maxPosition) {
// All buffered data has been read, let's get some more
if (eofReached) {
return false;
}
int retryCount = 0;
int length;
do {
if (retryCount > MAX_RETRY_COUNT) {
throw new IOException("Exceeded maximum number of attempts to read next chunk of data");
}
length = nextChunk();
// If outputBuffer != null, it means that data is being read off of the InputStream
if (outputBuffer == null) {
retryCount++;
}
} while (length == 0);
if (length == -1) {
return false;
}
}
return true;
}
/**
* {@inheritDoc}
* <p>
* Note: This implementation will only skip up to the end of the buffered
* data, potentially skipping 0 bytes.
*/
@Override
public long skip(long n) {
abortIfNeeded();
int available = maxPosition - currentPosition;
if (n > available) {
n = available;
}
if (n < 0) {
return 0;
}
currentPosition += n;
return n;
}
@Override
public int available() {
abortIfNeeded();
return maxPosition - currentPosition;
}
@Override
public void close() throws IOException {
in.close();
try {
// Throw away the unprocessed data
cipher.doFinal();
} catch (BadPaddingException | IllegalBlockSizeException ex) {
// Swallow the exception
}
currentPosition = maxPosition = 0;
abortIfNeeded();
}
@Override
public boolean markSupported() {
return false;
}
@Override
public void mark(int readlimit) {
// mark/reset not supported
}
@Override
public void reset() throws IOException {
throw new IOException("mark/reset not supported");
}
/**
* Reads and process the next chunk of data into memory.
*
* @return the length of the data chunk read and processed, or -1 if end of
* stream.
* @throws IOException if there is an IO exception from the underlying input stream
*/
protected int nextChunk() throws IOException {
abortIfNeeded();
if (eofReached) {
return -1;
}
outputBuffer = null;
int length = in.read(inputBuffer);
if (length == -1) {
return endOfFileReached();
}
outputBuffer = cipher.update(inputBuffer, 0, length);
currentPosition = 0;
return maxPosition = (outputBuffer == null ? 0 : outputBuffer.length);
}
protected int endOfFileReached() {
eofReached = true;
try {
outputBuffer = cipher.doFinal();
if (outputBuffer == null) {
return -1;
}
currentPosition = 0;
return maxPosition = outputBuffer.length;
} catch (IllegalBlockSizeException | BadPaddingException ignore) {
// Swallow exceptions
}
return -1;
}
}
| 2,282 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/CryptoFactory.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import software.amazon.encryption.s3.S3EncryptionClientException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
public class CryptoFactory {
public static Cipher createCipher(String algorithm, Provider provider)
throws NoSuchPaddingException, NoSuchAlgorithmException {
// if the user has specified a provider, go with that.
if (provider != null) {
return Cipher.getInstance(algorithm, provider);
}
// Otherwise, go with the default provider.
return Cipher.getInstance(algorithm);
}
public static KeyGenerator generateKey(String algorithm, Provider provider) {
KeyGenerator generator;
try {
if (provider == null) {
generator = KeyGenerator.getInstance(algorithm);
} else {
generator = KeyGenerator.getInstance(algorithm, provider);
}
} catch (NoSuchAlgorithmException e) {
throw new S3EncryptionClientException("Unable to generate a(n) " + algorithm + " data key", e);
}
return generator;
}
}
| 2,283 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/ApiNameVersion.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.core.ApiName;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.function.Consumer;
/**
* Provides the information for the ApiName APIs for the AWS SDK
*/
public class ApiNameVersion {
private static final ApiName API_NAME = ApiNameVersion.apiNameWithVersion();
// This is used in overrideConfiguration
public static final Consumer<AwsRequestOverrideConfiguration.Builder> API_NAME_INTERCEPTOR =
builder -> builder.addApiName(API_NAME);
public static final String NAME = "AmazonS3Encrypt";
public static final String API_VERSION_UNKNOWN = "3-unknown";
public static ApiName apiNameWithVersion() {
return ApiName.builder()
.name(NAME)
.version(apiVersion())
.build();
}
private static String apiVersion() {
try {
final Properties properties = new Properties();
final ClassLoader loader = ApiNameVersion.class.getClassLoader();
final InputStream inputStream = loader.getResourceAsStream("project.properties");
// In some cases, e.g. native images, there is no way to load files,
// and the inputStream returned is null.
if (inputStream == null) {
return API_VERSION_UNKNOWN;
}
properties.load(inputStream);
return properties.getProperty("version");
} catch (final IOException ex) {
return API_VERSION_UNKNOWN;
}
}
}
| 2,284 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/MultipartUploadObjectPipeline.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.AbortMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.SdkPartType;
import software.amazon.awssdk.services.s3.model.UploadPartRequest;
import software.amazon.awssdk.services.s3.model.UploadPartResponse;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.encryption.s3.S3EncryptionClientException;
import software.amazon.encryption.s3.algorithms.AlgorithmSuite;
import software.amazon.encryption.s3.materials.CryptographicMaterialsManager;
import software.amazon.encryption.s3.materials.EncryptionMaterials;
import software.amazon.encryption.s3.materials.EncryptionMaterialsRequest;
import javax.crypto.Cipher;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import static software.amazon.encryption.s3.internal.ApiNameVersion.API_NAME_INTERCEPTOR;
public class MultipartUploadObjectPipeline {
final private S3AsyncClient _s3AsyncClient;
final private CryptographicMaterialsManager _cryptoMaterialsManager;
final private MultipartContentEncryptionStrategy _contentEncryptionStrategy;
final private ContentMetadataEncodingStrategy _contentMetadataEncodingStrategy;
/**
* Map of data about in progress encrypted multipart uploads.
*/
private final Map<String, MultipartUploadMaterials> _multipartUploadMaterials;
private MultipartUploadObjectPipeline(Builder builder) {
this._s3AsyncClient = builder._s3AsyncClient;
this._cryptoMaterialsManager = builder._cryptoMaterialsManager;
this._contentEncryptionStrategy = builder._contentEncryptionStrategy;
this._contentMetadataEncodingStrategy = builder._contentMetadataEncodingStrategy;
this._multipartUploadMaterials = builder._multipartUploadMaterials;
}
public static Builder builder() {
return new Builder();
}
public CreateMultipartUploadResponse createMultipartUpload(CreateMultipartUploadRequest request) {
EncryptionMaterialsRequest.Builder requestBuilder = EncryptionMaterialsRequest.builder()
.s3Request(request);
EncryptionMaterials materials = _cryptoMaterialsManager.getEncryptionMaterials(requestBuilder.build());
MultipartEncryptedContent encryptedContent = _contentEncryptionStrategy.initMultipartEncryption(materials);
Map<String, String> metadata = new HashMap<>(request.metadata());
metadata = _contentMetadataEncodingStrategy.encodeMetadata(materials, encryptedContent.getIv(), metadata);
request = request.toBuilder()
.overrideConfiguration(API_NAME_INTERCEPTOR)
.metadata(metadata).build();
CreateMultipartUploadResponse response = _s3AsyncClient.createMultipartUpload(request).join();
MultipartUploadMaterials mpuMaterials = MultipartUploadMaterials.builder()
.fromEncryptionMaterials(materials)
.cipher(encryptedContent.getCipher())
.build();
_multipartUploadMaterials.put(response.uploadId(), mpuMaterials);
return response;
}
public UploadPartResponse uploadPart(UploadPartRequest request, RequestBody requestBody)
throws AwsServiceException, SdkClientException {
final AlgorithmSuite algorithmSuite = AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF;
final int blockSize = algorithmSuite.cipherBlockSizeBytes();
// Validate the partSize / contentLength in the request and requestBody
// There is similar logic in PutEncryptedObjectPipeline,
// but this uses non-async requestBody, so the code is not shared
final long partContentLength;
if (request.contentLength() != null) {
if (requestBody.optionalContentLength().isPresent() && !request.contentLength().equals(requestBody.optionalContentLength().get())) {
// if the contentLength values do not match, throw an exception, since we don't know which is correct
throw new S3EncryptionClientException("The contentLength provided in the request object MUST match the " +
"contentLength in the request body");
} else if (!requestBody.optionalContentLength().isPresent()) {
// no contentLength in request body, use the one in request
partContentLength = request.contentLength();
} else {
// only remaining case is when the values match, so either works here
partContentLength = request.contentLength();
}
} else {
partContentLength = requestBody.optionalContentLength().orElse(-1L);
}
final boolean isLastPart = request.sdkPartType() != null && request.sdkPartType().equals(SdkPartType.LAST);
final int cipherTagLength = isLastPart ? algorithmSuite.cipherTagLengthBytes() : 0;
final long ciphertextLength = partContentLength + cipherTagLength;
final boolean partSizeMultipleOfCipherBlockSize = 0 == (partContentLength % blockSize);
if (!isLastPart && !partSizeMultipleOfCipherBlockSize) {
throw new S3EncryptionClientException("Invalid part size: part sizes for encrypted multipart uploads must " +
"be multiples of the cipher block size (" + blockSize + ") with the exception of the last part.");
}
// Once we have (a valid) ciphertext length, set the request contentLength
UploadPartRequest actualRequest = request.toBuilder()
.overrideConfiguration(API_NAME_INTERCEPTOR)
.contentLength(ciphertextLength)
.build();
final String uploadId = actualRequest.uploadId();
final MultipartUploadMaterials materials = _multipartUploadMaterials.get(uploadId);
if (materials == null) {
throw new S3EncryptionClientException("No client-side information available on upload ID " + uploadId);
}
final UploadPartResponse response;
// Checks the parts are uploaded in series
materials.beginPartUpload(actualRequest.partNumber(), partContentLength);
Cipher cipher = materials.getCipher(materials.getIv());
try {
final AsyncRequestBody cipherAsyncRequestBody = new CipherAsyncRequestBody(AsyncRequestBody.fromInputStream(requestBody.contentStreamProvider().newStream(),
partContentLength, // this MUST be the original contentLength; it refers to the plaintext stream
Executors.newSingleThreadExecutor()), ciphertextLength, materials, cipher.getIV(), isLastPart);
// Ensure we haven't already seen the last part
if (isLastPart) {
if (materials.hasFinalPartBeenSeen()) {
throw new S3EncryptionClientException("This part was specified as the last part in a multipart " +
"upload, but a previous part was already marked as the last part. Only the last part of the " +
"upload should be marked as the last part.");
}
}
// Ensures parts are not retried to avoid corrupting ciphertext
AsyncRequestBody noRetryBody = new NoRetriesAsyncRequestBody(cipherAsyncRequestBody);
response = _s3AsyncClient.uploadPart(actualRequest, noRetryBody).join();
} finally {
materials.endPartUpload();
}
if (isLastPart) {
materials.setHasFinalPartBeenSeen(true);
}
return response;
}
public CompleteMultipartUploadResponse completeMultipartUpload(CompleteMultipartUploadRequest request)
throws AwsServiceException, SdkClientException {
String uploadId = request.uploadId();
final MultipartUploadMaterials uploadContext = _multipartUploadMaterials.get(uploadId);
if (uploadContext != null && !uploadContext.hasFinalPartBeenSeen()) {
throw new S3EncryptionClientException(
"Unable to complete an encrypted multipart upload without being told which part was the last. "
+ "Without knowing which part was the last, the encrypted data in Amazon S3 is incomplete and corrupt.");
}
CompleteMultipartUploadRequest actualRequest = request.toBuilder()
.overrideConfiguration(API_NAME_INTERCEPTOR)
.build();
CompleteMultipartUploadResponse response = _s3AsyncClient.completeMultipartUpload(actualRequest).join();
_multipartUploadMaterials.remove(uploadId);
return response;
}
public AbortMultipartUploadResponse abortMultipartUpload(AbortMultipartUploadRequest request) {
_multipartUploadMaterials.remove(request.uploadId());
AbortMultipartUploadRequest actualRequest = request.toBuilder()
.overrideConfiguration(API_NAME_INTERCEPTOR)
.build();
return _s3AsyncClient.abortMultipartUpload(actualRequest).join();
}
public void putLocalObject(RequestBody requestBody, String uploadId, OutputStream os) throws IOException {
final MultipartUploadMaterials materials = _multipartUploadMaterials.get(uploadId);
Cipher cipher = materials.getCipher(materials.getIv());
final InputStream cipherInputStream = new AuthenticatedCipherInputStream(requestBody.contentStreamProvider().newStream(), cipher);
try {
IoUtils.copy(cipherInputStream, os);
materials.setHasFinalPartBeenSeen(true);
} finally {
// This will create last part of MultiFileOutputStream upon close
IoUtils.closeQuietly(os, null);
}
}
public static class Builder {
private final Map<String, MultipartUploadMaterials> _multipartUploadMaterials =
Collections.synchronizedMap(new HashMap<>());
private final ContentMetadataEncodingStrategy _contentMetadataEncodingStrategy = ContentMetadataStrategy.OBJECT_METADATA;
private S3AsyncClient _s3AsyncClient;
private CryptographicMaterialsManager _cryptoMaterialsManager;
private SecureRandom _secureRandom;
// To Create Cipher which is used in during uploadPart requests.
private MultipartContentEncryptionStrategy _contentEncryptionStrategy;
private Builder() {
}
/**
* Note that this does NOT create a defensive clone of S3Client. Any modifications made to the wrapped
* S3Client will be reflected in this Builder.
*/
@SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "Pass mutability into wrapping client")
public Builder s3AsyncClient(S3AsyncClient s3AsyncClient) {
this._s3AsyncClient = s3AsyncClient;
return this;
}
public Builder cryptoMaterialsManager(CryptographicMaterialsManager cryptoMaterialsManager) {
this._cryptoMaterialsManager = cryptoMaterialsManager;
return this;
}
public Builder secureRandom(SecureRandom secureRandom) {
this._secureRandom = secureRandom;
return this;
}
public MultipartUploadObjectPipeline build() {
// Default to AesGcm since it is the only active (non-legacy) content encryption strategy
if (_contentEncryptionStrategy == null) {
_contentEncryptionStrategy = StreamingAesGcmContentStrategy
.builder()
.secureRandom(_secureRandom)
.build();
}
return new MultipartUploadObjectPipeline(this);
}
}
}
| 2,285 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/GetEncryptedObjectPipeline.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.encryption.s3.S3EncryptionClientException;
import software.amazon.encryption.s3.algorithms.AlgorithmSuite;
import software.amazon.encryption.s3.legacy.internal.AesCtrUtils;
import software.amazon.encryption.s3.legacy.internal.RangedGetUtils;
import software.amazon.encryption.s3.materials.CryptographicMaterialsManager;
import software.amazon.encryption.s3.materials.DecryptMaterialsRequest;
import software.amazon.encryption.s3.materials.DecryptionMaterials;
import software.amazon.encryption.s3.materials.EncryptedDataKey;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import static software.amazon.encryption.s3.internal.ApiNameVersion.API_NAME_INTERCEPTOR;
/**
* This class will determine the necessary mechanisms to decrypt objects returned from S3.
* Due to supporting various legacy modes, this is not a predefined pipeline like
* PutEncryptedObjectPipeline. There are several branches in this graph that are determined as more
* information is available from the returned object.
*/
public class GetEncryptedObjectPipeline {
private final S3AsyncClient _s3AsyncClient;
private final CryptographicMaterialsManager _cryptoMaterialsManager;
private final boolean _enableLegacyUnauthenticatedModes;
private final boolean _enableDelayedAuthentication;
private final long _bufferSize;
public static Builder builder() {
return new Builder();
}
private GetEncryptedObjectPipeline(Builder builder) {
this._s3AsyncClient = builder._s3AsyncClient;
this._cryptoMaterialsManager = builder._cryptoMaterialsManager;
this._enableLegacyUnauthenticatedModes = builder._enableLegacyUnauthenticatedModes;
this._enableDelayedAuthentication = builder._enableDelayedAuthentication;
this._bufferSize = builder._bufferSize;
}
public <T> CompletableFuture<T> getObject(GetObjectRequest getObjectRequest, AsyncResponseTransformer<GetObjectResponse, T> asyncResponseTransformer) {
// In async, decryption is done within a response transformation
String cryptoRange = RangedGetUtils.getCryptoRangeAsString(getObjectRequest.range());
GetObjectRequest adjustedRangeRequest = getObjectRequest.toBuilder()
.overrideConfiguration(API_NAME_INTERCEPTOR)
.range(cryptoRange)
.build();
if (!_enableLegacyUnauthenticatedModes && getObjectRequest.range() != null) {
throw new S3EncryptionClientException("Enable legacy unauthenticated modes to use Ranged Get.");
}
return _s3AsyncClient.getObject(adjustedRangeRequest, new DecryptingResponseTransformer<>(asyncResponseTransformer,
getObjectRequest));
}
private DecryptionMaterials prepareMaterialsFromRequest(final GetObjectRequest getObjectRequest, final GetObjectResponse getObjectResponse,
final ContentMetadata contentMetadata) {
AlgorithmSuite algorithmSuite = contentMetadata.algorithmSuite();
if (!_enableLegacyUnauthenticatedModes && algorithmSuite.isLegacy()) {
throw new S3EncryptionClientException("Enable legacy unauthenticated modes to use legacy content decryption: " + algorithmSuite.cipherName());
}
List<EncryptedDataKey> encryptedDataKeys = Collections.singletonList(contentMetadata.encryptedDataKey());
DecryptMaterialsRequest materialsRequest = DecryptMaterialsRequest.builder()
.s3Request(getObjectRequest)
.algorithmSuite(algorithmSuite)
.encryptedDataKeys(encryptedDataKeys)
.encryptionContext(contentMetadata.encryptedDataKeyContext())
.ciphertextLength(getObjectResponse.contentLength())
.build();
return _cryptoMaterialsManager.decryptMaterials(materialsRequest);
}
private class DecryptingResponseTransformer<T> implements AsyncResponseTransformer<GetObjectResponse, T> {
/**
* This is the customer-supplied transformer. This class must
* feed it plaintext so that it can transform the plaintext
* into type T.
*/
final AsyncResponseTransformer<GetObjectResponse, T> wrappedAsyncResponseTransformer;
final GetObjectRequest getObjectRequest;
ContentMetadata contentMetadata;
GetObjectResponse getObjectResponse;
DecryptionMaterials materials;
CompletableFuture<T> resultFuture;
DecryptingResponseTransformer(AsyncResponseTransformer<GetObjectResponse, T> wrappedAsyncResponseTransformer,
GetObjectRequest getObjectRequest) {
this.wrappedAsyncResponseTransformer = wrappedAsyncResponseTransformer;
this.getObjectRequest = getObjectRequest;
}
@Override
public CompletableFuture<T> prepare() {
resultFuture = wrappedAsyncResponseTransformer.prepare();
return resultFuture;
}
@Override
public void onResponse(GetObjectResponse response) {
getObjectResponse = response;
contentMetadata = ContentMetadataStrategy.decode(getObjectRequest, response);
materials = prepareMaterialsFromRequest(getObjectRequest, response, contentMetadata);
wrappedAsyncResponseTransformer.onResponse(response);
}
@Override
public void exceptionOccurred(Throwable error) {
wrappedAsyncResponseTransformer.exceptionOccurred(error);
}
@Override
public void onStream(SdkPublisher<ByteBuffer> ciphertextPublisher) {
long[] desiredRange = RangedGetUtils.getRange(materials.s3Request().range());
long[] cryptoRange = RangedGetUtils.getCryptoRange(materials.s3Request().range());
AlgorithmSuite algorithmSuite = materials.algorithmSuite();
SecretKey contentKey = materials.dataKey();
final int tagLength = algorithmSuite.cipherTagLengthBits();
byte[] iv = contentMetadata.contentIv();
if (algorithmSuite == AlgorithmSuite.ALG_AES_256_CTR_IV16_TAG16_NO_KDF) {
iv = AesCtrUtils.adjustIV(iv, cryptoRange[0]);
}
try {
final Cipher cipher = CryptoFactory.createCipher(algorithmSuite.cipherName(), materials.cryptoProvider());
switch (algorithmSuite) {
case ALG_AES_256_GCM_IV12_TAG16_NO_KDF:
cipher.init(Cipher.DECRYPT_MODE, contentKey, new GCMParameterSpec(tagLength, iv));
break;
case ALG_AES_256_CTR_IV16_TAG16_NO_KDF:
case ALG_AES_256_CBC_IV16_NO_KDF:
cipher.init(Cipher.DECRYPT_MODE, contentKey, new IvParameterSpec(iv));
break;
default:
throw new S3EncryptionClientException("Unknown algorithm: " + algorithmSuite.cipherName());
}
if (algorithmSuite.equals(AlgorithmSuite.ALG_AES_256_CBC_IV16_NO_KDF)
|| algorithmSuite.equals(AlgorithmSuite.ALG_AES_256_CTR_IV16_TAG16_NO_KDF)
|| _enableDelayedAuthentication) {
// CBC and GCM with delayed auth enabled use a standard publisher
CipherPublisher plaintextPublisher = new CipherPublisher(ciphertextPublisher,
getObjectResponse.contentLength(), desiredRange, contentMetadata.contentRange(), algorithmSuite.cipherTagLengthBits(), materials, iv);
wrappedAsyncResponseTransformer.onStream(plaintextPublisher);
} else {
// Use buffered publisher for GCM when delayed auth is not enabled
BufferedCipherPublisher plaintextPublisher = new BufferedCipherPublisher(ciphertextPublisher,
getObjectResponse.contentLength(), materials, iv, _bufferSize);
wrappedAsyncResponseTransformer.onStream(plaintextPublisher);
}
} catch (GeneralSecurityException e) {
throw new S3EncryptionClientException("Unable to " + algorithmSuite.cipherName() + " content decrypt.", e);
}
}
}
public static class Builder {
private S3AsyncClient _s3AsyncClient;
private CryptographicMaterialsManager _cryptoMaterialsManager;
private boolean _enableLegacyUnauthenticatedModes;
private boolean _enableDelayedAuthentication;
private long _bufferSize;
private Builder() {
}
/**
* Note that this does NOT create a defensive clone of S3Client. Any modifications made to the wrapped
* S3Client will be reflected in this Builder.
*/
@SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "Pass mutability into wrapping client")
public Builder s3AsyncClient(S3AsyncClient s3AsyncClient) {
this._s3AsyncClient = s3AsyncClient;
return this;
}
public Builder cryptoMaterialsManager(CryptographicMaterialsManager cryptoMaterialsManager) {
this._cryptoMaterialsManager = cryptoMaterialsManager;
return this;
}
public Builder enableLegacyUnauthenticatedModes(boolean enableLegacyUnauthenticatedModes) {
this._enableLegacyUnauthenticatedModes = enableLegacyUnauthenticatedModes;
return this;
}
public Builder bufferSize(long bufferSize) {
this._bufferSize = bufferSize;
return this;
}
public Builder enableDelayedAuthentication(boolean enableDelayedAuthentication) {
this._enableDelayedAuthentication = enableDelayedAuthentication;
return this;
}
public GetEncryptedObjectPipeline build() {
return new GetEncryptedObjectPipeline(this);
}
}
}
| 2,286 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/MultiFileOutputStream.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import software.amazon.encryption.s3.S3EncryptionClientException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import java.util.concurrent.Semaphore;
public class MultiFileOutputStream extends OutputStream implements OnFileDelete {
static final int DEFAULT_PART_SIZE = 5 << 20; // 5MB
private final File root;
private final String namePrefix;
private int filesCreated;
private long partSize = DEFAULT_PART_SIZE;
private long diskLimit = Long.MAX_VALUE;
private UploadObjectObserver observer;
/**
* Number of bytes that have been written to the current file.
*/
private int currFileBytesWritten;
/**
* Total number of bytes written to all files so far.
*/
private long totalBytesWritten;
private FileOutputStream os;
private boolean closed;
/**
* null means no blocking necessary.
*/
private Semaphore diskPermits;
/**
* Construct an instance to use the default temporary directory and temp
* file naming convention. The
* {@link #init(UploadObjectObserver, long, long)} must be called before
* this stream is considered fully initialized.
*/
public MultiFileOutputStream() {
root = new File(System.getProperty("java.io.tmpdir"));
namePrefix = yyMMdd_hhmmss() + "." + UUID.randomUUID();
}
/**
* Construct an instance to use the specified directory for temp file
* creations, and the specified prefix for temp file naming. The
* {@link #init(UploadObjectObserver, long, long)} must be called before
* this stream is considered fully initialized.
*/
public MultiFileOutputStream(File root, String namePrefix) {
if (root == null || !root.isDirectory() || !root.canWrite()) {
throw new IllegalArgumentException(root
+ " must be a writable directory");
}
if (namePrefix == null || namePrefix.trim().length() == 0) {
throw new IllegalArgumentException(
"Please specify a non-empty name prefix");
}
this.root = root;
this.namePrefix = namePrefix;
}
static String yyMMdd_hhmmss() {
return DateTimeFormat.forPattern("yyMMdd-hhmmss").print(new DateTime());
}
/**
* Used to initialize this stream. This method is an SPI (service provider
* interface) that is called from <code>S3EncryptionClient</code>.
* <p>
* Implementation of this method should never block.
*
* @param observer the upload object observer
* @param partSize part size for multipart upload
* @param diskLimit the maximum disk space to be used for this multipart upload
* @return this object
*/
public MultiFileOutputStream init(UploadObjectObserver observer,
long partSize, long diskLimit) {
if (observer == null) {
throw new IllegalArgumentException("Observer must be specified");
}
this.observer = observer;
if (diskLimit < partSize << 1) {
throw new IllegalArgumentException(
"Maximum temporary disk space must be at least twice as large as the part size: partSize="
+ partSize + ", diskSize=" + diskLimit);
}
this.partSize = partSize;
this.diskLimit = diskLimit;
final int max = (int) (diskLimit / partSize);
this.diskPermits = max < 0 ? null : new Semaphore(max);
return this;
}
/**
* This method would block as necessary if running out of disk space.
*/
@Override
public void write(int b) throws IOException {
fos().write(b);
currFileBytesWritten++;
totalBytesWritten++;
}
/**
* This method would block as necessary if running out of disk space.
*/
@Override
public void write(byte[] b) throws IOException {
if (b.length == 0) {
return;
}
fos().write(b);
currFileBytesWritten += b.length;
totalBytesWritten += b.length;
}
/**
* This method would block as necessary if running out of disk space.
*/
@Override
public void write(byte[] b, int off, int len) throws IOException {
if (b.length == 0) {
return;
}
fos().write(b, off, len);
currFileBytesWritten += len;
totalBytesWritten += len;
}
/**
* Returns the file output stream to be used for writing, blocking as
* necessary if running out of disk space.
*
* @throws InterruptedException if the running thread was interrupted
*/
private FileOutputStream fos() throws IOException {
if (closed) {
throw new IOException("Output stream is already closed");
}
if (os == null || currFileBytesWritten >= partSize) {
if (os != null) {
os.close();
// notify about the new file ready for processing
observer.onPartCreate(new PartCreationEvent(
getFile(filesCreated), filesCreated, false, this));
}
currFileBytesWritten = 0;
filesCreated++;
blockIfNecessary();
final File file = getFile(filesCreated);
os = new FileOutputStream(file);
}
return os;
}
@Override
public void onFileDelete(FileDeletionEvent event) {
if (diskPermits != null) {
diskPermits.release();
}
}
/**
* Blocks the running thread if running out of disk space.
*
* @throws S3EncryptionClientException if the running thread is interrupted while acquiring a
* semaphore
*/
private void blockIfNecessary() {
if (diskPermits == null || diskLimit == Long.MAX_VALUE) {
return;
}
try {
diskPermits.acquire();
} catch (InterruptedException e) {
// Don't want to re-interrupt, so it won't cause SDK stream to be
// closed in case the thread is reused for a different request
throw new S3EncryptionClientException(e.getMessage(), e);
}
}
@Override
public void flush() throws IOException {
if (os != null) {
os.flush();
}
}
@Override
public void close() throws IOException {
if (closed) {
return;
}
closed = true;
if (os != null) {
os.close();
File lastPart = getFile(filesCreated);
if (lastPart.length() == 0) {
if (!lastPart.delete()) {
LogFactory.getLog(getClass()).debug(
"Ignoring failure to delete empty file " + lastPart);
}
} else {
// notify about the new file ready for processing
observer.onPartCreate(new PartCreationEvent(
getFile(filesCreated), filesCreated, true, this));
}
}
}
public void cleanup() {
for (int i = 0; i < getNumFilesWritten(); i++) {
File f = getFile(i);
if (f.exists()) {
if (!f.delete()) {
LogFactory.getLog(getClass()).debug(
"Ignoring failure to delete file " + f);
}
}
}
}
/**
* @return the number of files written with the specified prefix with the
* part number as the file extension.
*/
public int getNumFilesWritten() {
return filesCreated;
}
public File getFile(int partNumber) {
return new File(root, namePrefix + "." + partNumber);
}
public long getPartSize() {
return partSize;
}
public File getRoot() {
return root;
}
public String getNamePrefix() {
return namePrefix;
}
public long getTotalBytesWritten() {
return totalBytesWritten;
}
public boolean isClosed() {
return closed;
}
public long getDiskLimit() {
return diskLimit;
}
}
| 2,287 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/FileDeletionEvent.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
/**
* A file deletion event.
*/
public class FileDeletionEvent {
// currently only a placeholder so method signature won't be affected by
// future changes
} | 2,288 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/CipherSubscriber.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.utils.BinaryUtils;
import software.amazon.encryption.s3.S3EncryptionClientSecurityException;
import software.amazon.encryption.s3.materials.CryptographicMaterials;
import javax.crypto.Cipher;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.util.concurrent.atomic.AtomicLong;
public class CipherSubscriber implements Subscriber<ByteBuffer> {
private final AtomicLong contentRead = new AtomicLong(0);
private final Subscriber<? super ByteBuffer> wrappedSubscriber;
private Cipher cipher;
private final Long contentLength;
private final CryptographicMaterials materials;
private byte[] iv;
private boolean isLastPart;
private byte[] outputBuffer;
CipherSubscriber(Subscriber<? super ByteBuffer> wrappedSubscriber, Long contentLength, CryptographicMaterials materials, byte[] iv, boolean isLastPart) {
this.wrappedSubscriber = wrappedSubscriber;
this.contentLength = contentLength;
this.materials = materials;
this.iv = iv;
cipher = materials.getCipher(iv);
this.isLastPart = isLastPart;
}
CipherSubscriber(Subscriber<? super ByteBuffer> wrappedSubscriber, Long contentLength, CryptographicMaterials materials, byte[] iv) {
// When no partType is specified, it's not multipart, so there's one part, which must be the last
this(wrappedSubscriber, contentLength, materials, iv, true);
}
@Override
public void onSubscribe(Subscription s) {
wrappedSubscriber.onSubscribe(s);
}
@Override
public void onNext(ByteBuffer byteBuffer) {
int amountToReadFromByteBuffer = getAmountToReadFromByteBuffer(byteBuffer);
if (amountToReadFromByteBuffer > 0) {
byte[] buf = BinaryUtils.copyBytesFrom(byteBuffer, amountToReadFromByteBuffer);
outputBuffer = cipher.update(buf, 0, amountToReadFromByteBuffer);
if (outputBuffer == null && amountToReadFromByteBuffer < cipher.getBlockSize()) {
// The underlying data is too short to fill in the block cipher
// This is true at the end of the file, so complete to get the final
// bytes
this.onComplete();
}
wrappedSubscriber.onNext(ByteBuffer.wrap(outputBuffer));
} else {
// Do nothing
wrappedSubscriber.onNext(byteBuffer);
}
}
private int getAmountToReadFromByteBuffer(ByteBuffer byteBuffer) {
// If content length is null, we should include everything in the cipher because the stream is essentially
// unbounded.
if (contentLength == null) {
return byteBuffer.remaining();
}
long amountReadSoFar = contentRead.getAndAdd(byteBuffer.remaining());
long amountRemaining = Math.max(0, contentLength - amountReadSoFar);
if (amountRemaining > byteBuffer.remaining()) {
return byteBuffer.remaining();
} else {
return Math.toIntExact(amountRemaining);
}
}
@Override
public void onError(Throwable t) {
wrappedSubscriber.onError(t);
}
@Override
public void onComplete() {
if (!isLastPart) {
// If this isn't the last part, skip doFinal, we aren't done
wrappedSubscriber.onComplete();
return;
}
try {
outputBuffer = cipher.doFinal();
// Send the final bytes to the wrapped subscriber
wrappedSubscriber.onNext(ByteBuffer.wrap(outputBuffer));
} catch (final GeneralSecurityException exception) {
// Forward error, else the wrapped subscriber waits indefinitely
wrappedSubscriber.onError(exception);
throw new S3EncryptionClientSecurityException(exception.getMessage(), exception);
}
wrappedSubscriber.onComplete();
}
} | 2,289 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/AuthenticatedCipherInputStream.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import software.amazon.encryption.s3.S3EncryptionClientSecurityException;
import javax.crypto.Cipher;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
public class AuthenticatedCipherInputStream extends CipherInputStream {
/**
* True if this input stream is currently involved in a multipart uploads;
* false otherwise. For multipart uploads, the doFinal method of the
* underlying cipher has to be triggered via the read methods rather than
* the close method, since we can't tell if closing the input stream is due
* to a recoverable error (in which case the cipher's doFinal method should
* never be called) or normal completion (where the cipher's doFinal method
* would need to be called if it was not a multipart upload).
*/
private final boolean multipart;
/**
* True if this is the last part of a multipart upload; false otherwise.
*/
private final boolean lastMultipart;
public AuthenticatedCipherInputStream(InputStream inputStream, Cipher cipher) {
this(inputStream, cipher, false, false);
}
public AuthenticatedCipherInputStream(InputStream inputStream, Cipher cipher,
boolean multipart, boolean lastMultipart) {
super(inputStream, cipher);
this.multipart = multipart;
this.lastMultipart = lastMultipart;
}
/**
* Authenticated ciphers call doFinal upon the last read,
* there is no need to do so upon close.
* @throws IOException from the wrapped InputStream
*/
@Override
public void close() throws IOException {
in.close();
currentPosition = maxPosition = 0;
abortIfNeeded();
}
@Override
protected int endOfFileReached() {
eofReached = true;
// Skip doFinal if it's a multipart upload but not for the last part of multipart upload
if (!multipart || lastMultipart) {
try {
outputBuffer = cipher.doFinal();
if (outputBuffer == null) {
return -1;
}
currentPosition = 0;
return maxPosition = outputBuffer.length;
} catch (GeneralSecurityException exception) {
// In an authenticated scheme, this indicates a security
// exception
throw new S3EncryptionClientSecurityException(exception.getMessage(), exception);
}
}
return -1;
}
}
| 2,290 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/ContentMetadata.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import software.amazon.encryption.s3.algorithms.AlgorithmSuite;
import software.amazon.encryption.s3.materials.EncryptedDataKey;
import java.util.Collections;
import java.util.Map;
public class ContentMetadata {
private final AlgorithmSuite _algorithmSuite;
private final EncryptedDataKey _encryptedDataKey;
private final String _encryptedDataKeyAlgorithm;
private final Map<String, String> _encryptedDataKeyContext;
private final byte[] _contentIv;
private final String _contentCipher;
private final String _contentCipherTagLength;
private final String _contentRange;
private ContentMetadata(Builder builder) {
_algorithmSuite = builder._algorithmSuite;
_encryptedDataKey = builder._encryptedDataKey;
_encryptedDataKeyAlgorithm = builder._encryptedDataKeyAlgorithm;
_encryptedDataKeyContext = builder._encryptedDataKeyContext;
_contentIv = builder._contentIv;
_contentCipher = builder._contentCipher;
_contentCipherTagLength = builder._contentCipherTagLength;
_contentRange = builder._contentRange;
}
public static Builder builder() {
return new Builder();
}
public AlgorithmSuite algorithmSuite() {
return _algorithmSuite;
}
public EncryptedDataKey encryptedDataKey() {
return _encryptedDataKey;
}
public String encryptedDataKeyAlgorithm() {
return _encryptedDataKeyAlgorithm;
}
/**
* Note that the underlying implementation uses a Collections.unmodifiableMap which is
* immutable.
*/
@SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "False positive; underlying"
+ " implementation is immutable")
public Map<String, String> encryptedDataKeyContext() {
return _encryptedDataKeyContext;
}
public byte[] contentIv() {
if (_contentIv == null) {
return null;
}
return _contentIv.clone();
}
public String contentCipher() {
return _contentCipher;
}
public String contentCipherTagLength() {
return _contentCipherTagLength;
}
public String contentRange() {
return _contentRange;
}
public static class Builder {
private AlgorithmSuite _algorithmSuite;
private EncryptedDataKey _encryptedDataKey;
private String _encryptedDataKeyAlgorithm;
private Map<String, String> _encryptedDataKeyContext;
private byte[] _contentIv;
private String _contentCipher;
private String _contentCipherTagLength;
public String _contentRange;
private Builder() {
}
public Builder algorithmSuite(AlgorithmSuite algorithmSuite) {
_algorithmSuite = algorithmSuite;
return this;
}
public Builder encryptedDataKey(EncryptedDataKey encryptedDataKey) {
_encryptedDataKey = encryptedDataKey;
return this;
}
public Builder encryptedDataKeyAlgorithm(String encryptedDataKeyAlgorithm) {
_encryptedDataKeyAlgorithm = encryptedDataKeyAlgorithm;
return this;
}
public Builder encryptedDataKeyContext(Map<String, String> encryptedDataKeyContext) {
_encryptedDataKeyContext = Collections.unmodifiableMap(encryptedDataKeyContext);
return this;
}
public Builder contentIv(byte[] contentIv) {
_contentIv = contentIv.clone();
return this;
}
public Builder contentRange(String contentRange) {
_contentRange = contentRange;
return this;
}
public ContentMetadata build() {
return new ContentMetadata(this);
}
}
}
| 2,291 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/NoRetriesAsyncRequestBody.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.encryption.s3.S3EncryptionClientException;
import java.nio.ByteBuffer;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* AsyncRequestBody which blocks re-subscription.
* This is useful when retrying is problematic,
* such as when uploading parts of a multipart upload.
*/
public class NoRetriesAsyncRequestBody implements AsyncRequestBody {
private final AsyncRequestBody wrappedAsyncRequestBody;
private final AtomicBoolean subscribeCalled = new AtomicBoolean(false);
public NoRetriesAsyncRequestBody(final AsyncRequestBody wrappedAsyncRequestBody) {
this.wrappedAsyncRequestBody = wrappedAsyncRequestBody;
}
@Override
public Optional<Long> contentLength() {
return wrappedAsyncRequestBody.contentLength();
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> subscriber) {
if (subscribeCalled.compareAndSet(false, true)) {
wrappedAsyncRequestBody.subscribe(subscriber);
} else {
throw new S3EncryptionClientException("Re-subscription is not supported! Retry the entire operation.");
}
}
}
| 2,292 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/AsyncContentEncryptionStrategy.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.encryption.s3.materials.EncryptionMaterials;
@FunctionalInterface
public interface AsyncContentEncryptionStrategy {
EncryptedContent encryptContent(EncryptionMaterials materials, AsyncRequestBody content);
}
| 2,293 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/BufferedCipherPublisher.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.encryption.s3.materials.CryptographicMaterials;
import java.nio.ByteBuffer;
public class BufferedCipherPublisher implements SdkPublisher<ByteBuffer> {
private final SdkPublisher<ByteBuffer> wrappedPublisher;
private final Long contentLength;
private final CryptographicMaterials materials;
private final byte[] iv;
private final long bufferSize;
public BufferedCipherPublisher(final SdkPublisher<ByteBuffer> wrappedPublisher, final Long contentLength,
final CryptographicMaterials materials, final byte[] iv, final long bufferSize) {
this.wrappedPublisher = wrappedPublisher;
this.contentLength = contentLength;
this.materials = materials;
this.iv = iv;
this.bufferSize = bufferSize;
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> subscriber) {
// Wrap the (customer) subscriber in a CipherSubscriber, then subscribe it
// to the wrapped (ciphertext) publisher
wrappedPublisher.subscribe(new BufferedCipherSubscriber(subscriber, contentLength, materials, iv, bufferSize));
}
}
| 2,294 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/CipherProvider.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import software.amazon.encryption.s3.S3EncryptionClientException;
import software.amazon.encryption.s3.S3EncryptionClientSecurityException;
import software.amazon.encryption.s3.materials.CryptographicMaterials;
import software.amazon.encryption.s3.materials.CryptographicMaterialsManager;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import java.util.Arrays;
/**
* Composes a CMM to provide S3 specific functionality
*/
public class CipherProvider {
private final CryptographicMaterialsManager cmm;
public CipherProvider(final CryptographicMaterialsManager cmm) {
this.cmm = cmm;
}
/**
* Given some materials and an IV, create and init a Cipher object.
* @param materials the materials which dictate e.g. algorithm suite
* @param iv the IV, it MUST be initialized before use
* @return a Cipher object, initialized and ready to use
*/
public static Cipher createAndInitCipher(final CryptographicMaterials materials, byte[] iv) {
// Validate that the IV has been populated. There is a small chance
// that an IV containing only 0s is (validly) randomly generated,
// but the tradeoff is worth the protection, and an IV of 0s is
// not entirely unlike randomly generating "password" as your password.
if (Arrays.equals(iv, new byte[iv.length])) {
throw new S3EncryptionClientSecurityException("IV has not been initialized!");
}
try {
Cipher cipher = CryptoFactory.createCipher(materials.algorithmSuite().cipherName(), materials.cryptoProvider());
switch (materials.algorithmSuite()) {
case ALG_AES_256_GCM_IV12_TAG16_NO_KDF:
cipher.init(materials.cipherMode().opMode(), materials.dataKey(), new GCMParameterSpec(materials.algorithmSuite().cipherTagLengthBits(), iv));
break;
case ALG_AES_256_CTR_IV16_TAG16_NO_KDF:
case ALG_AES_256_CBC_IV16_NO_KDF:
if (materials.cipherMode().opMode() == Cipher.ENCRYPT_MODE) {
throw new S3EncryptionClientException("Encryption is not supported for algorithm: " + materials.algorithmSuite().cipherName());
}
cipher.init(materials.cipherMode().opMode(), materials.dataKey(), new IvParameterSpec(iv));
break;
default:
throw new S3EncryptionClientException("Unknown algorithm: " + materials.algorithmSuite().cipherName());
}
return cipher;
} catch (Exception exception) {
throw new S3EncryptionClientException(exception.getMessage(), exception);
}
}
}
| 2,295 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/OnFileDelete.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
/**
* A service provider interface (SPI) used to notify the event of a file
* deletion.
*/
public interface OnFileDelete {
/**
* Called upon a file deletion event.
* <p>
* Implementation of this method should never block.
*
* @param event file deletion event
*/
void onFileDelete(FileDeletionEvent event);
} | 2,296 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/MultipartUploadMaterials.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import software.amazon.awssdk.services.s3.model.S3Request;
import software.amazon.encryption.s3.S3EncryptionClientException;
import software.amazon.encryption.s3.algorithms.AlgorithmSuite;
import software.amazon.encryption.s3.materials.CryptographicMaterials;
import software.amazon.encryption.s3.materials.EncryptionMaterials;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Provider;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
public class MultipartUploadMaterials implements CryptographicMaterials {
// Original request
private final S3Request _s3Request;
// Identifies what sort of crypto algorithms we want to use
private final AlgorithmSuite _algorithmSuite;
// Additional information passed into encrypted that is required on decryption as well
// Should NOT contain sensitive information
private final Map<String, String> _encryptionContext;
private final byte[] _plaintextDataKey;
private final Provider _cryptoProvider;
private long _plaintextLength;
private boolean hasFinalPartBeenSeen;
private final Cipher _cipher;
private MultipartUploadMaterials(Builder builder) {
this._s3Request = builder._s3Request;
this._algorithmSuite = builder._algorithmSuite;
this._encryptionContext = builder._encryptionContext;
this._plaintextDataKey = builder._plaintextDataKey;
this._cryptoProvider = builder._cryptoProvider;
this._plaintextLength = builder._plaintextLength;
this._cipher = builder._cipher;
}
static public Builder builder() {
return new Builder();
}
public final boolean hasFinalPartBeenSeen() {
return hasFinalPartBeenSeen;
}
public final void setHasFinalPartBeenSeen(boolean hasFinalPartBeenSeen) {
this.hasFinalPartBeenSeen = hasFinalPartBeenSeen;
}
/**
* Can be used to enforce serial uploads.
*/
private int partNumber;
/**
* True if a multipart upload is currently in progress; false otherwise.
*/
private volatile boolean partUploadInProgress;
/**
* When calling with an IV, sanity check that the given IV matches the
* one in the cipher. Then just return the cipher.
*/
@Override
public Cipher getCipher(byte[] iv) {
if (!Arrays.equals(iv, _cipher.getIV())) {
throw new S3EncryptionClientException("IVs in MultipartUploadMaterials do not match!");
}
return _cipher;
}
public byte[] getIv() {
return _cipher.getIV();
}
/**
* Can be used to check the next part number must either be the same (if it
* was a retry) or increment by exactly 1 during a serial part uploads.
* <p>
* As a side effect, the {@link #partUploadInProgress} will be set to true
* upon successful completion of this method. Caller of this method is
* responsible to call {@link #endPartUpload()} in a finally block once
* the respective part-upload is completed (either normally or abruptly).
*
* @throws S3EncryptionClientException if parallel part upload is detected
* @see #endPartUpload()
*/
protected void beginPartUpload(final int nextPartNumber, final long partContentLength) {
if (nextPartNumber < 1)
throw new IllegalArgumentException("part number must be at least 1");
if (partUploadInProgress) {
throw new S3EncryptionClientException(
"Parts are required to be uploaded in series");
}
synchronized (this) {
if (nextPartNumber - partNumber <= 1) {
partNumber = nextPartNumber;
partUploadInProgress = true;
incrementPlaintextSize(partContentLength);
} else {
throw new S3EncryptionClientException(
"Parts are required to be uploaded in series (partNumber="
+ partNumber + ", nextPartNumber="
+ nextPartNumber + ")");
}
}
}
/**
* Increments the plaintextSize as parts come in, checking to
* ensure that the max GCM size limit is not exceeded.
* @param lengthOfPartToAdd the length of the incoming part
* @return the new _plaintextLength value
*/
private synchronized long incrementPlaintextSize(final long lengthOfPartToAdd) {
if (_plaintextLength + lengthOfPartToAdd > AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF.cipherMaxContentLengthBytes()) {
throw new S3EncryptionClientException("The contentLength of the object you are attempting to encrypt exceeds" +
"the maximum length allowed for GCM encryption.");
}
_plaintextLength += lengthOfPartToAdd;
return _plaintextLength;
}
/**
* Used to mark the completion of a part upload before the next. Should be
* invoked in finally block, and must be preceded previously by a call to
* {@link #beginPartUpload(int, long)}.
*
* @see #beginPartUpload(int, long)
*/
protected void endPartUpload() {
partUploadInProgress = false;
}
@Override
public AlgorithmSuite algorithmSuite() {
return _algorithmSuite;
}
@Override
public S3Request s3Request() {
return _s3Request;
}
/**
* Note that the underlying implementation uses a Collections.unmodifiableMap which is
* immutable.
*/
@Override
@SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "False positive; underlying"
+ " implementation is immutable")
public Map<String, String> encryptionContext() {
return _encryptionContext;
}
@Override
public SecretKey dataKey() {
return new SecretKeySpec(_plaintextDataKey, algorithmSuite().dataKeyAlgorithm());
}
@Override
public Provider cryptoProvider() {
return _cryptoProvider;
}
@Override
public CipherMode cipherMode() {
return CipherMode.MULTIPART_ENCRYPT;
}
static public class Builder {
private S3Request _s3Request = null;
private AlgorithmSuite _algorithmSuite = AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF;
private Map<String, String> _encryptionContext = Collections.emptyMap();
private byte[] _plaintextDataKey = null;
private long _plaintextLength = 0;
private Provider _cryptoProvider = null;
private Cipher _cipher = null;
private Builder() {
}
public Builder s3Request(S3Request s3Request) {
_s3Request = s3Request;
return this;
}
public Builder algorithmSuite(AlgorithmSuite algorithmSuite) {
_algorithmSuite = algorithmSuite;
return this;
}
public Builder encryptionContext(Map<String, String> encryptionContext) {
_encryptionContext = encryptionContext == null
? Collections.emptyMap()
: Collections.unmodifiableMap(encryptionContext);
return this;
}
public Builder plaintextDataKey(byte[] plaintextDataKey) {
_plaintextDataKey = plaintextDataKey == null ? null : plaintextDataKey.clone();
return this;
}
public Builder cryptoProvider(Provider cryptoProvider) {
_cryptoProvider = cryptoProvider;
return this;
}
public Builder cipher(Cipher cipher) {
_cipher = cipher;
return this;
}
public Builder fromEncryptionMaterials(final EncryptionMaterials materials) {
_s3Request = materials.s3Request();
_algorithmSuite = materials.algorithmSuite();
_encryptionContext = materials.encryptionContext();
_plaintextDataKey = materials.plaintextDataKey();
_cryptoProvider = materials.cryptoProvider();
return this;
}
public MultipartUploadMaterials build() {
return new MultipartUploadMaterials(this);
}
}
} | 2,297 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/CipherAsyncRequestBody.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.encryption.s3.materials.CryptographicMaterials;
import java.nio.ByteBuffer;
import java.util.Optional;
/**
* An AsyncRequestBody which encrypts and decrypts data as it passes through
* using a configured Cipher instance.
*/
public class CipherAsyncRequestBody implements AsyncRequestBody {
private final AsyncRequestBody wrappedAsyncRequestBody;
private final Long ciphertextLength;
private final CryptographicMaterials materials;
private final byte[] iv;
public CipherAsyncRequestBody(final AsyncRequestBody wrappedAsyncRequestBody, final Long ciphertextLength, final CryptographicMaterials materials, final byte[] iv, final boolean isLastPart) {
this.wrappedAsyncRequestBody = wrappedAsyncRequestBody;
this.ciphertextLength = ciphertextLength;
this.materials = materials;
this.iv = iv;
}
public CipherAsyncRequestBody(final AsyncRequestBody wrappedAsyncRequestBody, final Long ciphertextLength, final CryptographicMaterials materials, final byte[] iv) {
// When no partType is specified, it's not multipart,
// so there's one part, which must be the last
this(wrappedAsyncRequestBody, ciphertextLength, materials, iv, true);
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> subscriber) {
wrappedAsyncRequestBody.subscribe(new CipherSubscriber(subscriber, contentLength().orElse(-1L), materials, iv));
}
@Override
public Optional<Long> contentLength() {
return Optional.of(ciphertextLength);
}
}
| 2,298 |
0 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3 | Create_ds/amazon-s3-encryption-client-java/src/main/java/software/amazon/encryption/s3/internal/ContentMetadataStrategy.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.encryption.s3.internal;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser;
import software.amazon.awssdk.protocols.jsoncore.JsonWriter;
import software.amazon.awssdk.protocols.jsoncore.JsonWriter.JsonGenerationException;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
import software.amazon.encryption.s3.S3EncryptionClientException;
import software.amazon.encryption.s3.algorithms.AlgorithmSuite;
import software.amazon.encryption.s3.materials.EncryptedDataKey;
import software.amazon.encryption.s3.materials.EncryptionMaterials;
import software.amazon.encryption.s3.materials.S3Keyring;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import static software.amazon.encryption.s3.S3EncryptionClientUtilities.INSTRUCTION_FILE_SUFFIX;
public abstract class ContentMetadataStrategy implements ContentMetadataEncodingStrategy, ContentMetadataDecodingStrategy {
private static final Base64.Encoder ENCODER = Base64.getEncoder();
private static final Base64.Decoder DECODER = Base64.getDecoder();
public static final ContentMetadataDecodingStrategy INSTRUCTION_FILE = new ContentMetadataDecodingStrategy() {
@Override
public ContentMetadata decodeMetadata(GetObjectRequest getObjectRequest, GetObjectResponse response) {
GetObjectRequest instructionGetObjectRequest = GetObjectRequest.builder()
.bucket(getObjectRequest.bucket())
.key(getObjectRequest.key() + INSTRUCTION_FILE_SUFFIX)
.build();
S3Client s3Client = S3Client.create();
ResponseInputStream<GetObjectResponse> instruction;
try {
instruction = s3Client.getObject(instructionGetObjectRequest);
} catch (NoSuchKeyException exception) {
// Most likely, the customer is attempting to decrypt an object
// which is not encrypted with the S3 EC.
throw new S3EncryptionClientException("Instruction file not found! Please ensure the object you are" +
" attempting to decrypt has been encrypted using the S3 Encryption Client.", exception);
}
Map<String, String> metadata = new HashMap<>();
JsonNodeParser parser = JsonNodeParser.create();
JsonNode objectNode = parser.parse(instruction);
for (Map.Entry<String, JsonNode> entry : objectNode.asObject().entrySet()) {
metadata.put(entry.getKey(), entry.getValue().asString());
}
return ContentMetadataStrategy.readFromMap(metadata, response);
}
};
public static final ContentMetadataStrategy OBJECT_METADATA = new ContentMetadataStrategy() {
@Override
public Map<String, String> encodeMetadata(EncryptionMaterials materials, byte[] iv,
Map<String, String> metadata) {
EncryptedDataKey edk = materials.encryptedDataKeys().get(0);
metadata.put(MetadataKeyConstants.ENCRYPTED_DATA_KEY_V2, ENCODER.encodeToString(edk.encryptedDatakey()));
metadata.put(MetadataKeyConstants.CONTENT_IV, ENCODER.encodeToString(iv));
metadata.put(MetadataKeyConstants.CONTENT_CIPHER, materials.algorithmSuite().cipherName());
metadata.put(MetadataKeyConstants.CONTENT_CIPHER_TAG_LENGTH, Integer.toString(materials.algorithmSuite().cipherTagLengthBits()));
metadata.put(MetadataKeyConstants.ENCRYPTED_DATA_KEY_ALGORITHM, new String(edk.keyProviderInfo(), StandardCharsets.UTF_8));
try (JsonWriter jsonWriter = JsonWriter.create()) {
jsonWriter.writeStartObject();
for (Entry<String, String> entry : materials.encryptionContext().entrySet()) {
jsonWriter.writeFieldName(entry.getKey()).writeValue(entry.getValue());
}
jsonWriter.writeEndObject();
String jsonEncryptionContext = new String(jsonWriter.getBytes(), StandardCharsets.UTF_8);
metadata.put(MetadataKeyConstants.ENCRYPTED_DATA_KEY_CONTEXT, jsonEncryptionContext);
} catch (JsonGenerationException e) {
throw new S3EncryptionClientException("Cannot serialize encryption context to JSON.", e);
}
return metadata;
}
@Override
public ContentMetadata decodeMetadata(GetObjectRequest request, GetObjectResponse response) {
return ContentMetadataStrategy.readFromMap(response.metadata(), response);
}
};
private static ContentMetadata readFromMap(Map<String, String> metadata, GetObjectResponse response) {
// Get algorithm suite
final String contentEncryptionAlgorithm = metadata.get(MetadataKeyConstants.CONTENT_CIPHER);
AlgorithmSuite algorithmSuite;
String contentRange = response.contentRange();
if (contentEncryptionAlgorithm == null
|| contentEncryptionAlgorithm.equals(AlgorithmSuite.ALG_AES_256_CBC_IV16_NO_KDF.cipherName())) {
algorithmSuite = AlgorithmSuite.ALG_AES_256_CBC_IV16_NO_KDF;
} else if (contentEncryptionAlgorithm.equals(AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF.cipherName())) {
algorithmSuite = (contentRange == null ) ? AlgorithmSuite.ALG_AES_256_GCM_IV12_TAG16_NO_KDF : AlgorithmSuite.ALG_AES_256_CTR_IV16_TAG16_NO_KDF;
} else {
throw new S3EncryptionClientException(
"Unknown content encryption algorithm: " + contentEncryptionAlgorithm);
}
// Do algorithm suite dependent decoding
byte[] edkCiphertext;
// Currently, this is not stored within the metadata,
// signal to keyring(s) intended for S3EC
final String keyProviderId = S3Keyring.KEY_PROVIDER_ID;
String keyProviderInfo;
switch (algorithmSuite) {
case ALG_AES_256_CBC_IV16_NO_KDF:
// Extract encrypted data key ciphertext
if (metadata.containsKey(MetadataKeyConstants.ENCRYPTED_DATA_KEY_V1)) {
edkCiphertext = DECODER.decode(metadata.get(MetadataKeyConstants.ENCRYPTED_DATA_KEY_V1));
} else if (metadata.containsKey(MetadataKeyConstants.ENCRYPTED_DATA_KEY_V2)) {
// when using v1 to encrypt in its default mode, it may use the v2 EDK key
// despite also using CBC as the content encryption algorithm, presumably due
// to how the v2 changes were backported to v1
edkCiphertext = DECODER.decode(metadata.get(MetadataKeyConstants.ENCRYPTED_DATA_KEY_V2));
} else {
// this shouldn't happen under normal circumstances- only if out-of-band modification
// to the metadata is performed. it is most likely that the data is unrecoverable in this case
throw new S3EncryptionClientException("Malformed object metadata! Could not find the encrypted data key.");
}
if (!metadata.containsKey(MetadataKeyConstants.ENCRYPTED_DATA_KEY_ALGORITHM)) {
/*
For legacy v1 EncryptionOnly objects,
there is no EDK algorithm given, it is either plain AES or RSA
In v3, we infer AES vs. RSA based on the length of the ciphertext.
In v1, whichever key material is provided in its EncryptionMaterials
is used to decrypt the EDK.
In v3, this is not possible as the keyring code is factored such that
the keyProviderInfo is known before the keyring is known.
Ciphertext size is expected to be reliable as no AES data key should
exceed 256 bits (32 bytes) + 16 padding bytes.
In the unlikely event that this assumption is false, the fix would be
to refactor the keyring to always use the material given instead of
inferring it this way.
*/
if (edkCiphertext.length > 48) {
keyProviderInfo = "RSA";
} else {
keyProviderInfo = "AES";
}
} else {
keyProviderInfo = metadata.get(MetadataKeyConstants.ENCRYPTED_DATA_KEY_ALGORITHM);
}
break;
case ALG_AES_256_GCM_IV12_TAG16_NO_KDF:
case ALG_AES_256_CTR_IV16_TAG16_NO_KDF:
// Check tag length
final int tagLength = Integer.parseInt(metadata.get(MetadataKeyConstants.CONTENT_CIPHER_TAG_LENGTH));
if (tagLength != algorithmSuite.cipherTagLengthBits()) {
throw new S3EncryptionClientException("Expected tag length (bits) of: "
+ algorithmSuite.cipherTagLengthBits()
+ ", got: " + tagLength);
}
// Extract encrypted data key ciphertext and provider id
edkCiphertext = DECODER.decode(metadata.get(MetadataKeyConstants.ENCRYPTED_DATA_KEY_V2));
keyProviderInfo = metadata.get(MetadataKeyConstants.ENCRYPTED_DATA_KEY_ALGORITHM);
break;
default:
throw new S3EncryptionClientException(
"Unknown content encryption algorithm: " + algorithmSuite.id());
}
// Build encrypted data key
EncryptedDataKey edk = EncryptedDataKey.builder()
.encryptedDataKey(edkCiphertext)
.keyProviderId(keyProviderId)
.keyProviderInfo(keyProviderInfo.getBytes(StandardCharsets.UTF_8))
.build();
// Get encrypted data key encryption context
final Map<String, String> encryptionContext = new HashMap<>();
final String jsonEncryptionContext = metadata.get(MetadataKeyConstants.ENCRYPTED_DATA_KEY_CONTEXT);
try {
JsonNodeParser parser = JsonNodeParser.create();
JsonNode objectNode = parser.parse(jsonEncryptionContext);
for (Map.Entry<String, JsonNode> entry : objectNode.asObject().entrySet()) {
encryptionContext.put(entry.getKey(), entry.getValue().asString());
}
} catch (Exception e) {
throw new RuntimeException(e);
}
// Get content iv
byte[] iv = DECODER.decode(metadata.get(MetadataKeyConstants.CONTENT_IV));
return ContentMetadata.builder()
.algorithmSuite(algorithmSuite)
.encryptedDataKey(edk)
.encryptedDataKeyContext(encryptionContext)
.contentIv(iv)
.contentRange(contentRange)
.build();
}
public static ContentMetadata decode(GetObjectRequest request, GetObjectResponse response) {
Map<String, String> metadata = response.metadata();
ContentMetadataDecodingStrategy strategy;
if (metadata != null
&& metadata.containsKey(MetadataKeyConstants.CONTENT_IV)
&& (metadata.containsKey(MetadataKeyConstants.ENCRYPTED_DATA_KEY_V1)
|| metadata.containsKey(MetadataKeyConstants.ENCRYPTED_DATA_KEY_V2))) {
strategy = OBJECT_METADATA;
} else {
strategy = INSTRUCTION_FILE;
}
return strategy.decodeMetadata(request, response);
}
}
| 2,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.