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