自2024年7月31日起, AWS SDK for Java 1.x已进入维护模式,并将于2025年12月31日end-of-support
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
Amazon S3 使用客户端主密钥进行客户端加密
以下示例使用 AmazonS3 EncryptionClient V2Builder 类创建启用了 Amazon S3 客户端加密的客户端。启用后,您 Amazon S3 使用此客户端上传到的任何对象都将被加密。您 Amazon S3 使用此客户端获得的任何对象都将自动解密。
注意
以下示例演示了对客户管理的 Amazon S3 客户端主密钥使用客户端加密。要了解如何使用 AWS KMS托管密钥加密,请参阅使用托AWS KMS管密钥进行Amazon S3 客户端加密。
启用客户端 Amazon S3 加密时,您可以从两种加密模式中进行选择:严格认证或经过身份验证。以下部分说明了如何启用每种类型。要了解每种模式使用哪些算法,请参阅CryptoMode定义。
必需的导入
为这些示例导入以下类。
导入
import com.amazonaws.ClientConfiguration; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3EncryptionClientV2Builder; import com.amazonaws.services.s3.AmazonS3EncryptionV2; import com.amazonaws.services.s3.model.CryptoConfigurationV2; import com.amazonaws.services.s3.model.CryptoMode; import com.amazonaws.services.s3.model.EncryptionMaterials; import com.amazonaws.services.s3.model.StaticEncryptionMaterialsProvider;
经严格身份验证加密
如果未指定 CryptoMode
,则默认模式为经严格身份验证加密。
要显式启用此模式,请在 withCryptoConfiguration
方法中指定 StrictAuthenticatedEncryption
值。
注意
要使用客户端经身份验证加密,您必须将最新的 Bouncy Castle jar
代码
AmazonS3EncryptionV2 s3Encryption = AmazonS3EncryptionClientV2Builder.standard() .withRegion(Regions.US_WEST_2) .withCryptoConfiguration(new CryptoConfigurationV2().withCryptoMode((CryptoMode.StrictAuthenticatedEncryption))) .withEncryptionMaterialsProvider(new StaticEncryptionMaterialsProvider(new EncryptionMaterials(secretKey))) .build(); s3Encryption.putObject(bucket_name, ENCRYPTED_KEY2, "This is the 2nd content to encrypt");
经身份验证加密模式
使用 AuthenticatedEncryption
模式时,在加密期间会应用改进的密钥包装算法。在此模式下解密时,该算法会验证已解密对象的完整性,如果检查失败,则引发异常。有关经身份验证加密模式工作原理的更多详细信息,请参阅博客文章 Amazon S3 Client-Side Authenticated Encryption
注意
要使用客户端经身份验证加密,您必须将最新的 Bouncy Castle jar
要启用此模式,请在 withCryptoConfiguration
方法中指定 AuthenticatedEncryption
值。
代码
AmazonS3EncryptionV2 s3EncryptionClientV2 = AmazonS3EncryptionClientV2Builder.standard() .withRegion(Regions.DEFAULT_REGION) .withClientConfiguration(new ClientConfiguration()) .withCryptoConfiguration(new CryptoConfigurationV2().withCryptoMode(CryptoMode.AuthenticatedEncryption)) .withEncryptionMaterialsProvider(new StaticEncryptionMaterialsProvider(new EncryptionMaterials(secretKey))) .build(); s3EncryptionClientV2.putObject(bucket_name, ENCRYPTED_KEY1, "This is the 1st content to encrypt");