Path: blob/master/code_examples/java_examples/S3Examples/S3ClientSideEncryptionAsymmetricMasterKey.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.KeyFactory;9import java.security.KeyPair;10import java.security.KeyPairGenerator;11import java.security.NoSuchAlgorithmException;12import java.security.PrivateKey;13import java.security.PublicKey;14import java.security.SecureRandom;15import java.security.spec.InvalidKeySpecException;16import java.security.spec.PKCS8EncodedKeySpec;17import java.security.spec.X509EncodedKeySpec;1819import com.amazonaws.AmazonServiceException;20import com.amazonaws.SdkClientException;21import com.amazonaws.auth.profile.ProfileCredentialsProvider;22import com.amazonaws.services.s3.AmazonS3;23import com.amazonaws.services.s3.AmazonS3EncryptionClientBuilder;24import com.amazonaws.services.s3.model.EncryptionMaterials;25import com.amazonaws.services.s3.model.ObjectMetadata;26import com.amazonaws.services.s3.model.PutObjectRequest;27import com.amazonaws.services.s3.model.S3Object;28import com.amazonaws.services.s3.model.StaticEncryptionMaterialsProvider;29import com.amazonaws.util.IOUtils;3031public class S3ClientSideEncryptionAsymmetricMasterKey {3233public static void main(String[] args) throws Exception {34String clientRegion = "*** Client region ***";35String bucketName = "*** Bucket name ***";36String objectKeyName = "*** Key name ***";37String rsaKeyDir = System.getProperty("java.io.tmpdir");38String publicKeyName = "public.key";39String privateKeyName = "private.key";4041// Generate a 1024-bit RSA key pair.42KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");43keyGenerator.initialize(1024, new SecureRandom());44KeyPair origKeyPair = keyGenerator.generateKeyPair();4546// To see how it works, save and load the key pair to and from the file system.47saveKeyPair(rsaKeyDir, publicKeyName, privateKeyName, origKeyPair);48KeyPair keyPair = loadKeyPair(rsaKeyDir, publicKeyName, privateKeyName, "RSA");4950try {51// Create the encryption client.52EncryptionMaterials encryptionMaterials = new EncryptionMaterials(keyPair);53AmazonS3 s3EncryptionClient = AmazonS3EncryptionClientBuilder.standard()54.withCredentials(new ProfileCredentialsProvider())55.withEncryptionMaterials(new StaticEncryptionMaterialsProvider(encryptionMaterials))56.withRegion(clientRegion)57.build();5859// Create a new object.60byte[] plaintext = "S3 Object Encrypted Using Client-Side Asymmetric Master Key.".getBytes();61S3Object object = new S3Object();62object.setKey(objectKeyName);63object.setObjectContent(new ByteArrayInputStream(plaintext));64ObjectMetadata metadata = new ObjectMetadata();65metadata.setContentLength(plaintext.length);6667// Upload the object. The encryption client automatically encrypts it.68PutObjectRequest putRequest = new PutObjectRequest(bucketName,69object.getKey(),70object.getObjectContent(),71metadata);72s3EncryptionClient.putObject(putRequest);7374// Download and decrypt the object.75S3Object downloadedObject = s3EncryptionClient.getObject(bucketName, object.getKey());76byte[] decrypted = IOUtils.toByteArray(downloadedObject.getObjectContent());7778// Verify that the data that you downloaded is the same as the original data.79System.out.println("Plaintext: " + new String(plaintext));80System.out.println("Decrypted text: " + new String(decrypted));81}82catch(AmazonServiceException e) {83// The call was transmitted successfully, but Amazon S3 couldn't process84// it, so it returned an error response.85e.printStackTrace();86}87catch(SdkClientException e) {88// Amazon S3 couldn't be contacted for a response, or the client89// couldn't parse the response from Amazon S3.90e.printStackTrace();91}92}9394private static void saveKeyPair(String dir,95String publicKeyName,96String privateKeyName,97KeyPair keyPair) throws IOException {98PrivateKey privateKey = keyPair.getPrivate();99PublicKey publicKey = keyPair.getPublic();100101// Write the public key to the specified file.102X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());103FileOutputStream publicKeyOutputStream = new FileOutputStream(dir + File.separator + publicKeyName);104publicKeyOutputStream.write(x509EncodedKeySpec.getEncoded());105publicKeyOutputStream.close();106107// Write the private key to the specified file.108PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());109FileOutputStream privateKeyOutputStream = new FileOutputStream(dir + File.separator + privateKeyName);110privateKeyOutputStream.write(pkcs8EncodedKeySpec.getEncoded());111privateKeyOutputStream.close();112}113114private static KeyPair loadKeyPair(String dir,115String publicKeyName,116String privateKeyName,117String algorithm)118throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {119// Read the public key from the specified file.120File publicKeyFile = new File(dir + File.separator + publicKeyName);121FileInputStream publicKeyInputStream = new FileInputStream(publicKeyFile);122byte[] encodedPublicKey = new byte[(int) publicKeyFile.length()];123publicKeyInputStream.read(encodedPublicKey);124publicKeyInputStream.close();125126// Read the private key from the specified file.127File privateKeyFile = new File(dir + File.separator + privateKeyName);128FileInputStream privateKeyInputStream = new FileInputStream(privateKeyFile);129byte[] encodedPrivateKey = new byte[(int) privateKeyFile.length()];130privateKeyInputStream.read(encodedPrivateKey);131privateKeyInputStream.close();132133// Convert the keys into a key pair.134KeyFactory keyFactory = KeyFactory.getInstance(algorithm);135X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);136PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);137138PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);139PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);140141return new KeyPair(publicKey, privateKey);142}143}144145146