Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
awsdocs
GitHub Repository: awsdocs/amazon-s3-developer-guide
Path: blob/master/code_examples/java_examples/S3Examples/S3ClientSideEncryptionSymMasterKey.java
4084 views
1
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
// SPDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-s3-developer-guide/blob/master/LICENSE-SAMPLECODE.)
3
4
import java.io.ByteArrayInputStream;
5
import java.io.File;
6
import java.io.FileInputStream;
7
import java.io.FileOutputStream;
8
import java.io.IOException;
9
import java.security.InvalidKeyException;
10
import java.security.NoSuchAlgorithmException;
11
import java.security.spec.InvalidKeySpecException;
12
import java.security.spec.X509EncodedKeySpec;
13
14
import javax.crypto.KeyGenerator;
15
import javax.crypto.SecretKey;
16
import javax.crypto.spec.SecretKeySpec;
17
18
import com.amazonaws.AmazonServiceException;
19
import com.amazonaws.SdkClientException;
20
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
21
import com.amazonaws.services.s3.AmazonS3;
22
import com.amazonaws.services.s3.AmazonS3EncryptionClientBuilder;
23
import com.amazonaws.services.s3.model.EncryptionMaterials;
24
import com.amazonaws.services.s3.model.ObjectMetadata;
25
import com.amazonaws.services.s3.model.PutObjectRequest;
26
import com.amazonaws.services.s3.model.S3Object;
27
import com.amazonaws.services.s3.model.StaticEncryptionMaterialsProvider;
28
29
public class S3ClientSideEncryptionSymMasterKey {
30
31
public static void main(String[] args) throws Exception {
32
String clientRegion = "*** Client region ***";
33
String bucketName = "*** Bucket name ***";
34
String objectKeyName = "*** Object key name ***";
35
String masterKeyDir = System.getProperty("java.io.tmpdir");
36
String masterKeyName = "secret.key";
37
38
// Generate a symmetric 256-bit AES key.
39
KeyGenerator symKeyGenerator = KeyGenerator.getInstance("AES");
40
symKeyGenerator.init(256);
41
SecretKey symKey = symKeyGenerator.generateKey();
42
43
// To see how it works, save and load the key to and from the file system.
44
saveSymmetricKey(masterKeyDir, masterKeyName, symKey);
45
symKey = loadSymmetricAESKey(masterKeyDir, masterKeyName, "AES");
46
47
try {
48
// Create the Amazon S3 encryption client.
49
EncryptionMaterials encryptionMaterials = new EncryptionMaterials(symKey);
50
AmazonS3 s3EncryptionClient = AmazonS3EncryptionClientBuilder.standard()
51
.withCredentials(new ProfileCredentialsProvider())
52
.withEncryptionMaterials(new StaticEncryptionMaterialsProvider(encryptionMaterials))
53
.withRegion(clientRegion)
54
.build();
55
56
// Upload a new object. The encryption client automatically encrypts it.
57
byte[] plaintext = "S3 Object Encrypted Using Client-Side Symmetric Master Key.".getBytes();
58
s3EncryptionClient.putObject(new PutObjectRequest(bucketName,
59
objectKeyName,
60
new ByteArrayInputStream(plaintext),
61
new ObjectMetadata()));
62
63
// Download and decrypt the object.
64
S3Object downloadedObject = s3EncryptionClient.getObject(bucketName, objectKeyName);
65
byte[] decrypted = com.amazonaws.util.IOUtils.toByteArray(downloadedObject.getObjectContent());
66
67
// Verify that the data that you downloaded is the same as the original data.
68
System.out.println("Plaintext: " + new String(plaintext));
69
System.out.println("Decrypted text: " + new String(decrypted));
70
}
71
catch(AmazonServiceException e) {
72
// The call was transmitted successfully, but Amazon S3 couldn't process
73
// it, so it returned an error response.
74
e.printStackTrace();
75
}
76
catch(SdkClientException e) {
77
// Amazon S3 couldn't be contacted for a response, or the client
78
// couldn't parse the response from Amazon S3.
79
e.printStackTrace();
80
}
81
}
82
83
private static void saveSymmetricKey(String masterKeyDir, String masterKeyName, SecretKey secretKey) throws IOException {
84
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(secretKey.getEncoded());
85
FileOutputStream keyOutputStream = new FileOutputStream(masterKeyDir + File.separator + masterKeyName);
86
keyOutputStream.write(x509EncodedKeySpec.getEncoded());
87
keyOutputStream.close();
88
}
89
90
private static SecretKey loadSymmetricAESKey(String masterKeyDir, String masterKeyName, String algorithm)
91
throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException {
92
// Read the key from the specified file.
93
File keyFile = new File(masterKeyDir + File.separator + masterKeyName);
94
FileInputStream keyInputStream = new FileInputStream(keyFile);
95
byte[] encodedPrivateKey = new byte[(int) keyFile.length()];
96
keyInputStream.read(encodedPrivateKey);
97
keyInputStream.close();
98
99
// Reconstruct and return the master key.
100
return new SecretKeySpec(encodedPrivateKey, "AES");
101
}
102
}
103