使用Amazon KMS上传带有服务器端加密的S3对象时出错

时间:2015-03-26 17:49:45

标签: java encryption amazon-web-services amazon-s3

我在尝试重现亚马逊提供的示例代码时遇到以下异常:使用Amazon KMS(密钥管理服务)将S3对象上传到服务器端加密:

com.amazonaws.AmazonClientException: please use region-specific endpoint to access buckets located in regions that require V4 signing.
:: 
Caused by: com.amazonaws.services.s3.model.AmazonS3Exception: Requests specifying Server Side Encryption with AWS KMS managed keys require AWS Signature Version 4. (Service: Amazon S3; Status Code: 400; Error Code: InvalidArgument;

使用的代码是:

public void uploadServerSideEncryptedFileToS3( String bucketName , String key , String sourceFilePath , String masterKey ) {

    awsCredentials = new BasicAWSCredentials( awsAccessKey, awsSecretKey );
    PutObjectRequest putObjectRequest = new PutObjectRequest( bucketName,
                key , new File( sourceFilePath ) ).withSSEAwsKeyManagementParams( new SSEAwsKeyManagementParams( masterKey ) );

    ClientConfiguration clientConfiguration = new ClientConfiguration();
    clientConfiguration.setProtocol( Protocol.HTTPS );

    AmazonS3 connection = new AmazonS3Client( awsCredentials , clientConfiguration );
    connection.setRegion( com.amazonaws.regions.Region.getRegion( Regions.US_EAST_1 ) );
    PutObjectResult response = connection.putObject( putObjectRequest );
}

1 个答案:

答案 0 :(得分:0)

以下是我用于S3上传的代码

    @Test
public void testNoMetaData() {
    AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
    AmazonS3 amazonS3 = new AmazonS3Client(awsCredentials);
    amazonS3.setRegion(Region.getRegion(region));

    byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setSSEAlgorithm(SSEAlgorithm.KMS.getAlgorithm());
    InputStream inputStream = new ByteArrayInputStream(bytes);
    PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, metadata);

    putObjectRequest.withSSEAwsKeyManagementParams(new SSEAwsKeyManagementParams(awsKmsKeyId));
    amazonS3.putObject(putObjectRequest);
}