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