Amazon Simple Storage Service
开发人员指南 (API Version 2006-03-01)
AWS 服务或AWS文档中描述的功能,可能因地区/位置而异。请点击 Amazon AWS 入门,可查看中国地区的具体差异

示例 1:使用客户端对称主密钥加密和上传文件

此部分提供使用适用于 Java 的 AWS 开发工具包执行以下操作的示例代码:

  • 首先创建一个 256 位的 AES 对称主密钥并将其保存到文件中。

  • 使用首先加密客户端上示例数据的 S3 加密客户端将一个对象上传到 Amazon S3。示例还将下载该对象,并验证数据是否相同。

示例 1a:创建对称主密钥

运行此代码,首先生成一个 256 位的 AES 对称主密钥,以用于面向 Amazon S3 的加密上传。示例会将主密钥保存到 temp 目录中的一个文件 (secret.key) 中 (在 Windows 上,是 c:\Users\<username>\AppData\Local\Tmp 文件夹)。

有关如何创建和测试有效示例的说明,请参阅 使用 AWS SDK for Java

Copy
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; import java.util.Arrays; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.junit.Assert; public class GenerateSymmetricMasterKey { private static final String keyDir = System.getProperty("java.io.tmpdir"); private static final String keyName = "secret.key"; public static void main(String[] args) throws Exception { //Generate symmetric 256 bit AES key. KeyGenerator symKeyGenerator = KeyGenerator.getInstance("AES"); symKeyGenerator.init(256); SecretKey symKey = symKeyGenerator.generateKey(); //Save key. saveSymmetricKey(keyDir, symKey); //Load key. SecretKey symKeyLoaded = loadSymmetricAESKey(keyDir, "AES"); Assert.assertTrue(Arrays.equals(symKey.getEncoded(), symKeyLoaded.getEncoded())); } public static void saveSymmetricKey(String path, SecretKey secretKey) throws IOException { X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec( secretKey.getEncoded()); FileOutputStream keyfos = new FileOutputStream(path + "/" + keyName); keyfos.write(x509EncodedKeySpec.getEncoded()); keyfos.close(); } public static SecretKey loadSymmetricAESKey(String path, String algorithm) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException{ //Read private key from file. File keyFile = new File(path + "/" + keyName); FileInputStream keyfis = new FileInputStream(keyFile); byte[] encodedPrivateKey = new byte[(int)keyFile.length()]; keyfis.read(encodedPrivateKey); keyfis.close(); //Generate secret key. return new SecretKeySpec(encodedPrivateKey, "AES"); } }

此代码示例仅作示范用途。对于生产使用,您应该咨询您的安全工程师,了解如何获取或生成客户端主密钥。

示例 1b:使用对称密钥将一个文件上传到 Amazon S3

运行此代码,使用之前代码示例中创建的对称主密钥来加密示例数据。示例使用 S3 加密客户端来加密客户端上的数据,然后将其上传到 Amazon S3。

有关如何创建和测试有效示例的说明,请参阅 使用 AWS SDK for Java

Copy
import java.io.ByteArrayInputStream; import java.util.Arrays; import java.util.Iterator; import java.util.UUID; import javax.crypto.SecretKey; import org.apache.commons.io.IOUtils; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.junit.Assert; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3EncryptionClient; import com.amazonaws.services.s3.model.EncryptionMaterials; import com.amazonaws.services.s3.model.ListVersionsRequest; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectRequest; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectSummary; import com.amazonaws.services.s3.model.S3VersionSummary; import com.amazonaws.services.s3.model.StaticEncryptionMaterialsProvider; import com.amazonaws.services.s3.model.VersionListing; public class S3ClientSideEncryptionWithSymmetricMasterKey { private static final String masterKeyDir = System.getProperty("java.io.tmpdir"); private static final String bucketName = UUID.randomUUID() + "-" + DateTimeFormat.forPattern("yyMMdd-hhmmss").print(new DateTime()); private static final String objectKey = UUID.randomUUID().toString(); public static void main(String[] args) throws Exception { SecretKey mySymmetricKey = GenerateSymmetricMasterKey .loadSymmetricAESKey(masterKeyDir, "AES"); EncryptionMaterials encryptionMaterials = new EncryptionMaterials( mySymmetricKey); AmazonS3EncryptionClient encryptionClient = new AmazonS3EncryptionClient( new ProfileCredentialsProvider(), new StaticEncryptionMaterialsProvider(encryptionMaterials)); // Create the bucket encryptionClient.createBucket(bucketName); // Upload object using the encryption client. byte[] plaintext = "Hello World, S3 Client-side Encryption Using Asymmetric Master Key!" .getBytes(); System.out.println("plaintext's length: " + plaintext.length); encryptionClient.putObject(new PutObjectRequest(bucketName, objectKey, new ByteArrayInputStream(plaintext), new ObjectMetadata())); // Download the object. S3Object downloadedObject = encryptionClient.getObject(bucketName, objectKey); byte[] decrypted = IOUtils.toByteArray(downloadedObject .getObjectContent()); // Verify same data. Assert.assertTrue(Arrays.equals(plaintext, decrypted)); deleteBucketAndAllContents(encryptionClient); } private static void deleteBucketAndAllContents(AmazonS3 client) { System.out.println("Deleting S3 bucket: " + bucketName); ObjectListing objectListing = client.listObjects(bucketName); while (true) { for ( Iterator<?> iterator = objectListing.getObjectSummaries().iterator(); iterator.hasNext(); ) { S3ObjectSummary objectSummary = (S3ObjectSummary) iterator.next(); client.deleteObject(bucketName, objectSummary.getKey()); } if (objectListing.isTruncated()) { objectListing = client.listNextBatchOfObjects(objectListing); } else { break; } }; VersionListing list = client.listVersions(new ListVersionsRequest().withBucketName(bucketName)); for ( Iterator<?> iterator = list.getVersionSummaries().iterator(); iterator.hasNext(); ) { S3VersionSummary s = (S3VersionSummary)iterator.next(); client.deleteVersion(bucketName, s.getKey(), s.getVersionId()); } client.deleteBucket(bucketName); } }