- Java
-
Quando utilizzi AWS SDK for Java per caricare un oggetto, puoi utilizzare la crittografia lato server per crittografarlo. Per richiedere la crittografia lato server, utilizza la proprietà ObjectMetadata
della PutObjectRequest
per impostare l'intestazione della richiesta x-amz-server-side-encryption
. Quando si utilizza il metodo putObject()
di AmazonS3Client
, Amazon S3 cripta i dati e li salva.
È anche possibile richiedere la crittografia lato server durante il caricamento di oggetti con l'API per il caricamento in più parti:
-
Quando si utilizza l'API per il caricamento in più parti di alto livello, si utilizza i metodi TransferManager
per applicare la crittografia lato server agli oggetti durante il loro caricamento. È possibile utilizzare uno qualsiasi dei metodi di caricamento che accetta ObjectMetadata
come parametro. Per ulteriori informazioni, consulta Caricamento di un oggetto utilizzando il caricamento in più parti.
-
Quando si utilizza l'API per il caricamento in più parti di basso livello, si specifica la crittografia lato server quando si avvia il caricamento in più parti. Si aggiungi la proprietà ObjectMetadata
mediante una chiamata al metodo InitiateMultipartUploadRequest.setObjectMetadata()
. Per ulteriori informazioni, consulta Utilizzo degli SDK AWS (API di basso livello).
Non puoi direttamente modificare lo stato di crittografia di un oggetto (la crittografia di un oggetto non crittografato o la decrittografia dell'oggetto crittografato). Per modificare lo stato di crittografia di un oggetto, effettuare una copia dell'oggetto, specificando lo stato di crittografia per la copia e poi eliminare l'oggetto originale. Amazon S3 esegue la crittografia dell'oggetto copiato solo se hai effettuato una richiesta specifica di crittografia lato server. Per richiedere la crittografia dell'oggetto copiato tramite l'API Java, utilizza la proprietà ObjectMetadata
per specificare la crittografia lato server in CopyObjectRequest
, come mostrato nell'esempio di codice Java riportato di seguito.
Esempio
L'esempio che segue mostra come impostare la crittografia lato server utilizzando AWS SDK for Java. Mostra come eseguire le seguenti operazioni:
Carica un nuovo oggetto utilizzando la crittografia lato server.
Modifica lo stato di crittografia di un oggetto (in questo esempio, crittografare un oggetto precedentemente non crittografato) eseguendo una copia dell'oggetto.
Controlla lo stato di crittografia dell'oggetto.
Per ulteriori informazioni sulla crittografia lato server, consulta Utilizzo di REST API. Per istruzioni su come creare e testare un esempio di utilizzo, consulta Test degli esempi di codice Java di Amazon S3.
import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.internal.SSEResultBase;
import com.amazonaws.services.s3.model.*;
import java.io.ByteArrayInputStream;
public class SpecifyServerSideEncryption {
public static void main(String[] args) {
Regions clientRegion = Regions.DEFAULT_REGION;
String bucketName = "*** Bucket name ***";
String keyNameToEncrypt = "*** Key name for an object to upload and encrypt ***";
String keyNameToCopyAndEncrypt = "*** Key name for an unencrypted object to be encrypted by copying ***";
String copiedObjectKeyName = "*** Key name for the encrypted copy of the unencrypted object ***";
try {
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withRegion(clientRegion)
.withCredentials(new ProfileCredentialsProvider())
.build();
// Upload an object and encrypt it with SSE.
uploadObjectWithSSEEncryption(s3Client, bucketName, keyNameToEncrypt);
// Upload a new unencrypted object, then change its encryption state
// to encrypted by making a copy.
changeSSEEncryptionStatusByCopying(s3Client,
bucketName,
keyNameToCopyAndEncrypt,
copiedObjectKeyName);
} catch (AmazonServiceException e) {
// The call was transmitted successfully, but Amazon S3 couldn't process
// it, so it returned an error response.
e.printStackTrace();
} catch (SdkClientException e) {
// Amazon S3 couldn't be contacted for a response, or the client
// couldn't parse the response from Amazon S3.
e.printStackTrace();
}
}
private static void uploadObjectWithSSEEncryption(AmazonS3 s3Client, String bucketName, String keyName) {
String objectContent = "Test object encrypted with SSE";
byte[] objectBytes = objectContent.getBytes();
// Specify server-side encryption.
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(objectBytes.length);
objectMetadata.setSSEAlgorithm(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION);
PutObjectRequest putRequest = new PutObjectRequest(bucketName,
keyName,
new ByteArrayInputStream(objectBytes),
objectMetadata);
// Upload the object and check its encryption status.
PutObjectResult putResult = s3Client.putObject(putRequest);
System.out.println("Object \"" + keyName + "\" uploaded with SSE.");
printEncryptionStatus(putResult);
}
private static void changeSSEEncryptionStatusByCopying(AmazonS3 s3Client,
String bucketName,
String sourceKey,
String destKey) {
// Upload a new, unencrypted object.
PutObjectResult putResult = s3Client.putObject(bucketName, sourceKey, "Object example to encrypt by copying");
System.out.println("Unencrypted object \"" + sourceKey + "\" uploaded.");
printEncryptionStatus(putResult);
// Make a copy of the object and use server-side encryption when storing the copy.
CopyObjectRequest request = new CopyObjectRequest(bucketName,
sourceKey,
bucketName,
destKey);
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setSSEAlgorithm(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION);
request.setNewObjectMetadata(objectMetadata);
// Perform the copy operation and display the copy's encryption status.
CopyObjectResult response = s3Client.copyObject(request);
System.out.println("Object \"" + destKey + "\" uploaded with SSE.");
printEncryptionStatus(response);
// Delete the original, unencrypted object, leaving only the encrypted copy in Amazon S3.
s3Client.deleteObject(bucketName, sourceKey);
System.out.println("Unencrypted object \"" + sourceKey + "\" deleted.");
}
private static void printEncryptionStatus(SSEResultBase response) {
String encryptionStatus = response.getSSEAlgorithm();
if (encryptionStatus == null) {
encryptionStatus = "Not encrypted with SSE";
}
System.out.println("Object encryption status is: " + encryptionStatus);
}
}
- .NET
-
Quando carichi un oggetto, puoi indirizzare Amazon S3 per crittografarlo. Per modificare lo stato di crittografia di un oggetto esistente, effettuare una copia dell'oggetto ed eliminare l'oggetto di origine. Per impostazione predefinita, l'operazione di copia crittografa la destinazione solo se si richiede esplicitamente la crittografia lato server dell'oggetto di destinazione. Per specificare la crittografia lato server nella CopyObjectRequest
, aggiungi quanto segue:
ServerSideEncryptionMethod = ServerSideEncryptionMethod.AES256
Per un esempio di come copiare un oggetto, consulta Uso degli SDK AWS.
Nel seguente esempio viene caricato un oggetto. Nella richiesta l'esempio indirizza Amazon S3 per crittografare l'oggetto. L'esempio poi recupera i metadati dell'oggetto e verifica i metodi di crittografia utilizzati. Per informazioni su come creare e testare un esempio di utilizzo, consulta Esecuzione degli esempi di codice .NET di Amazon S3.
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using System;
using System.Threading.Tasks;
namespace Amazon.DocSamples.S3
{
class SpecifyServerSideEncryptionTest
{
private const string bucketName = "*** bucket name ***";
private const string keyName = "*** key name for object created ***";
// Specify your bucket region (an example region is shown).
private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2;
private static IAmazonS3 client;
public static void Main()
{
client = new AmazonS3Client(bucketRegion);
WritingAnObjectAsync().Wait();
}
static async Task WritingAnObjectAsync()
{
try
{
var putRequest = new PutObjectRequest
{
BucketName = bucketName,
Key = keyName,
ContentBody = "sample text",
ServerSideEncryptionMethod = ServerSideEncryptionMethod.AES256
};
var putResponse = await client.PutObjectAsync(putRequest);
// Determine the encryption state of an object.
GetObjectMetadataRequest metadataRequest = new GetObjectMetadataRequest
{
BucketName = bucketName,
Key = keyName
};
GetObjectMetadataResponse response = await client.GetObjectMetadataAsync(metadataRequest);
ServerSideEncryptionMethod objectEncryption = response.ServerSideEncryptionMethod;
Console.WriteLine("Encryption method used: {0}", objectEncryption.ToString());
}
catch (AmazonS3Exception e)
{
Console.WriteLine("Error encountered ***. Message:'{0}' when writing an object", e.Message);
}
catch (Exception e)
{
Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
}
}
}
}
- PHP
-
Questo argomento mostra come utilizzare le classi della versione 3 di AWS SDK for PHP per aggiungere crittografia lato server agli oggetti che si stanno caricando su Amazon Simple Storage Service (Amazon S3). Si presume che siano già state seguite le istruzioni riportate in Utilizzo dell'AWS SDK for PHP ed esecuzione degli esempi in PHP e che AWS SDK for PHP sia stato correttamente installato.
Per caricare un oggetto su Amazon S3, si utilizza il metodo Aws\S3\S3Client::putObject(). Per aggiungere l'intestazione di richiesta x-amz-server-side-encryption
alla richiesta di caricamento, specificare il parametroServerSideEncryption
con il valore AES256
, come mostrato nel seguente esempio di codice. Per ulteriori informazioni sulla crittografia lato server delle richieste, consultare Utilizzo di REST API.
require 'vendor/autoload.php';
use Aws\S3\S3Client;
$bucket = '*** Your Bucket Name ***';
$keyname = '*** Your Object Key ***';
// $filepath should be an absolute path to a file on disk.
$filepath = '*** Your File Path ***';
$s3 = new S3Client([
'version' => 'latest',
'region' => 'us-east-1'
]);
// Upload a file with server-side encryption.
$result = $s3->putObject([
'Bucket' => $bucket,
'Key' => $keyname,
'SourceFile' => $filepath,
'ServerSideEncryption' => 'AES256',
]);
Nella risposta Amazon S3 restituisce l'intestazione x-amz-server-side-encryption
con il valore dell'algoritmo di crittografia utilizzato per crittografare i dati dell'oggetto.
Quando si caricano oggetti di grandi dimensioni utilizzando l'API per il caricamento in più parti, è possibile specificare la crittografia lato server per gli oggetti che si stanno caricando, come segue:
-
Quando si utilizza l'API per il caricamento in più parti di basso livello, specificare la crittografia lato server quando viene chiamato il metodo Aws\S3\S3Client::createMultipartUpload(). Per aggiungere l'intestazione di richiesta x-amz-server-side-encryption
alla richiesta, specificare la chiave array
del parametro ServerSideEncryption
con il valore AES256
. Per ulteriori informazioni sull'API per il caricamento in più parti di basso livello, consulta Utilizzo degli SDK AWS (API di basso livello).
-
Quando si utilizza l'API per il caricamento in più parti di alto livello, specificare la crittografia lato server utilizzando il parametro ServerSideEncryption
del metodo CreateMultipartUpload. Per un esempio di utilizzo del metodo setOption()
con l'API per il caricamento in più parti di alto livello, consulta Caricamento di un oggetto utilizzando il caricamento in più parti.
Per determinare lo stato di crittografia di un oggetto esistente, recuperare i metadati dell'oggetto richiamando il metodo Aws\S3\S3Client::headObject(), come mostrato nell'esempio di codice PHP riportato di seguito.
require 'vendor/autoload.php';
use Aws\S3\S3Client;
$bucket = '*** Your Bucket Name ***';
$keyname = '*** Your Object Key ***';
$s3 = new S3Client([
'version' => 'latest',
'region' => 'us-east-1'
]);
// Check which server-side encryption algorithm is used.
$result = $s3->headObject([
'Bucket' => $bucket,
'Key' => $keyname,
]);
echo $result['ServerSideEncryption'];
Per modificare lo stato di crittografia di un oggetto esistente, effettuare una copia dell'oggetto utilizzando il metodo Aws\S3\S3Client::copyObject() ed eliminare l'oggetto di origine. Per default, copyObject()
non esegue la crittografia della destinazione, a meno che non si richieda esplicitamente la crittografia lato server dell'oggetto di destinazione utilizzando il parametro ServerSideEncryption
con il valore AES256
. Il seguente esempio di codice PHP esegue una copia di un oggetto e aggiunge la crittografia lato server all'oggetto copiato.
require 'vendor/autoload.php';
use Aws\S3\S3Client;
$sourceBucket = '*** Your Source Bucket Name ***';
$sourceKeyname = '*** Your Source Object Key ***';
$targetBucket = '*** Your Target Bucket Name ***';
$targetKeyname = '*** Your Target Object Key ***';
$s3 = new S3Client([
'version' => 'latest',
'region' => 'us-east-1'
]);
// Copy an object and add server-side encryption.
$s3->copyObject([
'Bucket' => $targetBucket,
'Key' => $targetKeyname,
'CopySource' => "{$sourceBucket}/{$sourceKeyname}",
'ServerSideEncryption' => 'AES256',
]);
- Ruby
-
Quando si utilizza l'AWS SDK for Ruby per caricare un oggetto, è possibile specificare di crittografare l'oggetto quando inattivo con la crittografia lato server (SSE). Dopo essere stato letto, l'oggetto viene automaticamente decrittografato.
Il seguente esempio di AWS SDK for Ruby versione 3 dimostra la modalità di indicazione dell'esecuzione della crittografia di un file caricato su Amazon S3 quando inattivo.
require "aws-sdk-s3"
# Wraps Amazon S3 object actions.
class ObjectPutSseWrapper
attr_reader :object
# @param object [Aws::S3::Object] An existing Amazon S3 object.
def initialize(object)
@object = object
end
def put_object_encrypted(object_content, encryption)
@object.put(body: object_content, server_side_encryption: encryption)
true
rescue Aws::Errors::ServiceError => e
puts "Couldn't put your content to #{object.key}. Here's why: #{e.message}"
false
end
end
def run_demo
bucket_name = "doc-example-bucket"
object_key = "my-encrypted-content"
object_content = "This is my super-secret content."
encryption = "AES256"
wrapper = ObjectPutSseWrapper.new(Aws::S3::Object.new(bucket_name, object_content))
return unless wrapper.put_object_encrypted(object_content, encryption)
puts "Put your content into #{bucket_name}:#{object_key} and encrypted it with #{encryption}."
end
run_demo if $PROGRAM_NAME == __FILE__
Per un esempio di come caricare un oggetto senza SSE, consulta Caricamento degli oggetti.
L'esempio di codice seguente dimostra come determinare lo stato di crittografia di un oggetto esistente.
require "aws-sdk-s3"
# Wraps Amazon S3 object actions.
class ObjectGetEncryptionWrapper
attr_reader :object
# @param object [Aws::S3::Object] An existing Amazon S3 object.
def initialize(object)
@object = object
end
# Gets the object into memory.
#
# @return [Aws::S3::Types::GetObjectOutput, nil] The retrieved object data if successful; otherwise nil.
def get_object
@object.get
rescue Aws::Errors::ServiceError => e
puts "Couldn't get object #{@object.key}. Here's why: #{e.message}"
end
end
# Replace bucket name and object key with an existing bucket and object that you own.
def run_demo
bucket_name = "doc-example-bucket"
object_key = "my-object.txt"
wrapper = ObjectGetEncryptionWrapper.new(Aws::S3::Object.new(bucket_name, object_key))
obj_data = wrapper.get_object
return unless obj_data
encryption = obj_data.server_side_encryption.nil? ? "no" : obj_data.server_side_encryption
puts "Object #{object_key} uses #{encryption} encryption."
end
run_demo if $PROGRAM_NAME == __FILE__
Se la crittografia lato server non viene utilizzata per l'oggetto archiviato in Amazon S3, il metodo restituisce null.
Per modificare lo stato di crittografia di un oggetto esistente, effettuare una copia dell'oggetto ed eliminare l'oggetto di origine. Per default, i metodi di copia non eseguono la crittografia della destinazione, a meno che non si richieda esplicitamente la crittografia lato server. È possibile richiedere la crittografia dell'oggetto di destinazione specificando il valore server_side_encryption
nell'argomento hash delle opzioni, come mostrato nel seguente esempio di codice Ruby. L'esempio di codice dimostra come copiare un oggetto e crittografare la copia.
require "aws-sdk-s3"
# Wraps Amazon S3 object actions.
class ObjectCopyEncryptWrapper
attr_reader :source_object
# @param source_object [Aws::S3::Object] An existing Amazon S3 object. This is used as the source object for
# copy actions.
def initialize(source_object)
@source_object = source_object
end
# Copy the source object to the specified target bucket, rename it with the target key, and encrypt it.
#
# @param target_bucket [Aws::S3::Bucket] An existing Amazon S3 bucket where the object is copied.
# @param target_object_key [String] The key to give the copy of the object.
# @return [Aws::S3::Object, nil] The copied object when successful; otherwise, nil.
def copy_object(target_bucket, target_object_key, encryption)
@source_object.copy_to(bucket: target_bucket.name, key: target_object_key, server_side_encryption: encryption)
target_bucket.object(target_object_key)
rescue Aws::Errors::ServiceError => e
puts "Couldn't copy #{@source_object.key} to #{target_object_key}. Here's why: #{e.message}"
end
end
# Replace the source and target bucket names with existing buckets you own and replace the source object key
# with an existing object in the source bucket.
def run_demo
source_bucket_name = "doc-example-bucket1"
source_key = "my-source-file.txt"
target_bucket_name = "doc-example-bucket2"
target_key = "my-target-file.txt"
target_encryption = "AES256"
source_bucket = Aws::S3::Bucket.new(source_bucket_name)
wrapper = ObjectCopyEncryptWrapper.new(source_bucket.object(source_key))
target_bucket = Aws::S3::Bucket.new(target_bucket_name)
target_object = wrapper.copy_object(target_bucket, target_key, target_encryption)
return unless target_object
puts "Copied #{source_key} from #{source_bucket_name} to #{target_object.bucket_name}:#{target_object.key} and "\
"encrypted the target with #{target_object.server_side_encryption} encryption."
end
run_demo if $PROGRAM_NAME == __FILE__