

La AWS SDK per .NET V3 è entrata in modalità manutenzione.

[Ti consigliamo di migrare alla V4.AWS SDK per .NET](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/welcome.html) Per ulteriori dettagli e informazioni su come eseguire la migrazione, consulta il nostro annuncio sulla modalità di [manutenzione](https://aws.amazon.com/blogs/developer/aws-sdk-for-net-v3-maintenance-mode-announcement/).

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# Utilizzo dello storage Internet di Amazon Simple Storage Service
<a name="s3-apis-intro"></a>

 AWS SDK per .NET Supporta [Amazon S3](https://aws.amazon.com/s3/), che è lo storage per Internet. È concepito per rendere più accessibili agli sviluppatori risorse informatiche su grande scala per il Web.

## APIs
<a name="w2aac19c15c21b5"></a>

 AWS SDK per .NET Fornisce APIs i client Amazon S3. Ti APIs consentono di lavorare con risorse Amazon S3 come bucket e articoli. Per visualizzare il set completo di APIs Amazon S3, consulta quanto segue:
+ [AWS SDK per .NET Riferimento all'API](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/) (e scorri fino a «Amazon.S3").
+ [Documentazione](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.html) sulla crittografia Amazon.Extensions.S3

Amazon S3 APIs è fornito dai seguenti pacchetti: NuGet 
+ [AWSSDK.S3](https://www.nuget.org/packages/AWSSDK.S3)
+ [Crittografia Amazon.Extensions.S3](https://www.nuget.org/packages/Amazon.Extensions.S3.Encryption)

## Prerequisiti
<a name="w2aac19c15c21b7"></a>

[Prima di iniziare, assicurati di aver configurato l'ambiente e il progetto.](net-dg-config.md) Consulta anche le informazioni contenute in[Funzionalità dell'SDK](net-dg-sdk-features.md).

## Esempi in questo documento
<a name="s3-apis-examples"></a>

I seguenti argomenti di questo documento mostrano come utilizzarlo AWS SDK per .NET per lavorare con Amazon S3.
+ [Utilizzo delle chiavi KMS per la crittografia S3](kms-keys-s3-encryption.md)

## Esempi in altri documenti
<a name="s3-apis-examples-other"></a>

I seguenti collegamenti alla [Amazon S3 Developer Guide](https://docs.aws.amazon.com/AmazonS3/latest/userguide/) forniscono ulteriori esempi su come utilizzarla per AWS SDK per .NET lavorare con Amazon S3.

**Nota**  
Sebbene questi esempi e considerazioni aggiuntive sulla programmazione siano stati creati per la versione 3 di Using .NET Framework, sono validi anche per le versioni successive di che AWS SDK per .NET utilizzano .NET Core. AWS SDK per .NET Talvolta sono necessarie piccole modifiche al codice.

**Esempi di programmazione in Amazon S3**
+  [Gestione ACLs](https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-using-dot-net-sdk.html) 
+  [Creazione di un bucket](https://docs.aws.amazon.com/AmazonS3/latest/dev/create-bucket-get-location-example.html#create-bucket-get-location-dotnet) 
+  [Caricamento di un oggetto](https://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjSingleOpNET.html) 
+  [[Caricamento multiparte con l'API di alto livello (Amazon.S3.Transfer). TransferUtility](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TTransferUtility.html))](https://docs.aws.amazon.com/AmazonS3/latest/dev/usingHLmpuDotNet.html) 
+  [Caricamento in più parti con l'API di basso livello](https://docs.aws.amazon.com/AmazonS3/latest/dev/usingLLmpuDotNet.html) 
+  [Elenco degli oggetti](https://docs.aws.amazon.com/AmazonS3/latest/dev/list-obj-version-enabled-bucket.html#list-obj-version-enabled-bucket-sdk-examples) 
+  [Elenco delle chiavi](https://docs.aws.amazon.com/AmazonS3/latest/dev/ListingObjectKeysUsingNetSDK.html) 
+  [Recupero di un oggetto](https://docs.aws.amazon.com/AmazonS3/latest/dev/RetrievingObjectUsingNetSDK.html) 
+  [Copia di un oggetto](https://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjectUsingNetSDK.html) 
+  [Copia di un oggetto con l'API per il caricamento in più parti](https://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjctsUsingLLNetMPUapi.html) 
+  [Eliminazione di un oggetto](https://docs.aws.amazon.com/AmazonS3/latest/dev/DeletingOneObjectUsingNetSDK.html) 
+  [Eliminazione di più oggetti](https://docs.aws.amazon.com/AmazonS3/latest/dev/DeletingMultipleObjectsUsingNetSDK.html) 
+  [Ripristino di un oggetto](https://docs.aws.amazon.com/AmazonS3/latest/dev/restore-object-dotnet.html) 
+  [Configurazione di un bucket per le notifiche](https://docs.aws.amazon.com/AmazonS3/latest/dev/ways-to-add-notification-config-to-bucket.html) 
+  [Gestione del ciclo di vita di un oggetto](https://docs.aws.amazon.com/AmazonS3/latest/dev/manage-lifecycle-using-dot-net.html) 
+  [Generazione di un URL prefirmato per un oggetto](https://docs.aws.amazon.com/AmazonS3/latest/dev/ShareObjectPreSignedURLDotNetSDK.html) 
+  [Gestione di siti Web](https://docs.aws.amazon.com/AmazonS3/latest/dev/ConfigWebSiteDotNet.html) 
+  [Abilitazione della condivisione di risorse tra le origini (CORS)](https://docs.aws.amazon.com/AmazonS3/latest/dev/ManageCorsUsingDotNet.html) 

**Considerazioni aggiuntive sulla programmazione**
+  [Utilizzo di AWS SDK per .NET per la programmazione in Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingTheMPDotNetAPI.html) 
+  [Esecuzione di richieste mediante le credenziali temporanee per gli utenti IAM](https://docs.aws.amazon.com/AmazonS3/latest/dev/AuthUsingTempSessionTokenDotNet.html) 
+  [Esecuzione di richieste mediante le credenziali temporanee per gli utenti federati](https://docs.aws.amazon.com/AmazonS3/latest/dev/AuthUsingTempFederationTokenDotNet.html) 
+  [Specifica della crittografia lato server](https://docs.aws.amazon.com/AmazonS3/latest/dev/SSEUsingDotNetSDK.html) 
+  [Specifica della crittografia lato server con chiavi di crittografia fornite dal cliente](https://docs.aws.amazon.com/AmazonS3/latest/dev/sse-c-using-dot-net-sdk.html) 

# Utilizzo AWS KMS delle chiavi per la crittografia Amazon S3 nel AWS SDK per .NET
<a name="kms-keys-s3-encryption"></a>

Questo esempio mostra come utilizzare AWS Key Management Service le chiavi per crittografare gli oggetti Amazon S3. L'applicazione crea una chiave master del cliente (CMK) e la utilizza per creare un oggetto [AmazonS3 EncryptionClient](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3EncryptionClientV2.html) V2 per la crittografia lato client. L'applicazione utilizza quel client per creare un oggetto crittografato da un determinato file di testo in un bucket Amazon S3 esistente. Quindi decripta l'oggetto e ne visualizza il contenuto.

**avvertimento**  
Una classe simile chiamata `AmazonS3EncryptionClient` è obsoleta ed è meno sicura della classe. `AmazonS3EncryptionClientV2` Per migrare il codice esistente che utilizza, consulta. `AmazonS3EncryptionClient` [Migrazione del client di crittografia S3 (da V1 a V2)](s3-encryption-migration-v1-v2.md)

**Topics**
+ [Creare materiali di crittografia](#kms-s3-enc-mat)
+ [Crea e crittografa un oggetto Amazon S3](#kms-s3-create-ojbect)
+ [Codice completo](#kms-s3-complete-code)
+ [Ulteriori considerazioni](#kms-s3-additional)

## Creare materiali di crittografia
<a name="kms-s3-enc-mat"></a>

Il seguente frammento crea un `EncryptionMaterials` oggetto che contiene un ID di chiave KMS.

L'esempio [alla fine di questo argomento mostra questo](#kms-s3-complete-code) frammento in uso.

```
      // Create a customer master key (CMK) and store the result
      CreateKeyResponse createKeyResponse =
        await new AmazonKeyManagementServiceClient().CreateKeyAsync(new CreateKeyRequest());
      var kmsEncryptionContext = new Dictionary<string, string>();
      var kmsEncryptionMaterials = new EncryptionMaterialsV2(
        createKeyResponse.KeyMetadata.KeyId, KmsType.KmsContext, kmsEncryptionContext);
```

## Crea e crittografa un oggetto Amazon S3
<a name="kms-s3-create-ojbect"></a>

Il seguente frammento crea un `AmazonS3EncryptionClientV2` oggetto che utilizza i materiali di crittografia creati in precedenza. Utilizza quindi il client per creare e crittografare un nuovo oggetto Amazon S3.

L'esempio [alla fine di questo argomento mostra questo](#kms-s3-complete-code) frammento in uso.

```
    //
    // Method to create and encrypt an object in an S3 bucket
    static async Task<GetObjectResponse> CreateAndRetrieveObjectAsync(
      EncryptionMaterialsV2 materials, string bucketName,
      string fileName, string itemName)
    {
      // CryptoStorageMode.ObjectMetadata is required for KMS EncryptionMaterials
      var config = new AmazonS3CryptoConfigurationV2(SecurityProfile.V2AndLegacy)
      {
        StorageMode = CryptoStorageMode.ObjectMetadata
      };
      var s3EncClient = new AmazonS3EncryptionClientV2(config, materials);

      // Create, encrypt, and put the object
      await s3EncClient.PutObjectAsync(new PutObjectRequest
      {
        BucketName = bucketName,
        Key = itemName,
        ContentBody = File.ReadAllText(fileName)
      });

      // Get, decrypt, and return the object
      return await s3EncClient.GetObjectAsync(new GetObjectRequest
      {
        BucketName = bucketName,
        Key = itemName
      });
    }
```

## Codice completo
<a name="kms-s3-complete-code"></a>

Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.

### Riferimenti SDK
<a name="w2aac19c15c21c13c15b5b1"></a>

NuGet pacchetti:
+ [Amazon.Extensions.S3.Encryption](https://www.nuget.org/packages/Amazon.Extensions.S3.Encryption)

Elementi di programmazione:
+ [Spazio dei nomi Amazon.Extensions.S3.Encryption](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.html)

  Classe [AmazonS3 V2 EncryptionClient](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3EncryptionClientV2.html)

  Classe [AmazonS3 CryptoConfiguration V2](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3CryptoConfigurationV2.html)

  Classe [CryptoStorageMode](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.CryptoStorageMode.html)

  Classe [EncryptionMaterialsV2](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.EncryptionMaterialsV2.html)
+ [Spazio dei nomi Amazon.Extensions.S3.Encryption.Primitives](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.Primitives.html)

  Classe [KmsType](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.Primitives.KmsType.html)
+ [Namespace Amazon.S3.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/NS3Model.html)

  Classe [GetObjectRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TGetObjectRequest.html)

  Classe [GetObjectResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TGetObjectResponse.html)

  Classe [PutObjectRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TPutObjectRequest.html)
+ [Namespace Amazon. KeyManagementService](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/KeyManagementService/NKeyManagementService.html)

  Classe [AmazonKeyManagementServiceClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/KeyManagementService/TKeyManagementServiceClient.html)
+ [Namespace Amazon. KeyManagementService](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/KeyManagementService/NKeyManagementServiceModel.html).Modello

  Classe [CreateKeyRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/KeyManagementService/TCreateKeyRequest.html)

  Classe [CreateKeyResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/KeyManagementService/TCreateKeyResponse.html)

### Il codice
<a name="w2aac19c15c21c13c15b7b1"></a>

```
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Amazon.Extensions.S3.Encryption;
using Amazon.Extensions.S3.Encryption.Primitives;
using Amazon.S3.Model;
using Amazon.KeyManagementService;
using Amazon.KeyManagementService.Model;

namespace KmsS3Encryption
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to store text in an encrypted S3 object.
  class Program
  {
    private const int MaxArgs = 3;

    public static async Task Main(string[] args)
    {
      // Parse the command line and show help if necessary
      var parsedArgs = CommandLine.Parse(args);
      if((parsedArgs.Count == 0) || (parsedArgs.Count > MaxArgs))
      {
        PrintHelp();
        return;
      }

      // Get the application arguments from the parsed list
      string bucketName =
        CommandLine.GetArgument(parsedArgs, null, "-b", "--bucket-name");
      string fileName =
        CommandLine.GetArgument(parsedArgs, null, "-f", "--file-name");
      string itemName =
        CommandLine.GetArgument(parsedArgs, null, "-i", "--item-name");
      if(string.IsNullOrEmpty(bucketName) || (string.IsNullOrEmpty(fileName)))
        CommandLine.ErrorExit(
          "\nOne or more of the required arguments is missing or incorrect." +
          "\nRun the command with no arguments to see help.");
      if(!File.Exists(fileName))
        CommandLine.ErrorExit($"\nThe given file {fileName} doesn't exist.");
      if(string.IsNullOrEmpty(itemName))
        itemName = Path.GetFileName(fileName);

      // Create a customer master key (CMK) and store the result
      CreateKeyResponse createKeyResponse =
        await new AmazonKeyManagementServiceClient().CreateKeyAsync(new CreateKeyRequest());
      var kmsEncryptionContext = new Dictionary<string, string>();
      var kmsEncryptionMaterials = new EncryptionMaterialsV2(
        createKeyResponse.KeyMetadata.KeyId, KmsType.KmsContext, kmsEncryptionContext);

      // Create the object in the bucket, then display the content of the object
      var putObjectResponse =
        await CreateAndRetrieveObjectAsync(kmsEncryptionMaterials, bucketName, fileName, itemName);
      Stream stream = putObjectResponse.ResponseStream;
      StreamReader reader = new StreamReader(stream);
      Console.WriteLine(reader.ReadToEnd());
    }


    //
    // Method to create and encrypt an object in an S3 bucket
    static async Task<GetObjectResponse> CreateAndRetrieveObjectAsync(
      EncryptionMaterialsV2 materials, string bucketName,
      string fileName, string itemName)
    {
      // CryptoStorageMode.ObjectMetadata is required for KMS EncryptionMaterials
      var config = new AmazonS3CryptoConfigurationV2(SecurityProfile.V2AndLegacy)
      {
        StorageMode = CryptoStorageMode.ObjectMetadata
      };
      var s3EncClient = new AmazonS3EncryptionClientV2(config, materials);

      // Create, encrypt, and put the object
      await s3EncClient.PutObjectAsync(new PutObjectRequest
      {
        BucketName = bucketName,
        Key = itemName,
        ContentBody = File.ReadAllText(fileName)
      });

      // Get, decrypt, and return the object
      return await s3EncClient.GetObjectAsync(new GetObjectRequest
      {
        BucketName = bucketName,
        Key = itemName
      });
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine(
        "\nUsage: KmsS3Encryption -b <bucket-name> -f <file-name> [-i <item-name>]" +
        "\n  -b, --bucket-name: The name of an existing S3 bucket." +
        "\n  -f, --file-name: The name of a text file with content to encrypt and store in S3." +
        "\n  -i, --item-name: The name you want to use for the item." +
        "\n      If item-name isn't given, file-name will be used.");
    }

  }

  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class that represents a command line on the console or terminal.
  // (This is the same for all examples. When you have seen it once, you can ignore it.)
  static class CommandLine
  {
    //
    // Method to parse a command line of the form: "--key value" or "-k value".
    //
    // Parameters:
    // - args: The command-line arguments passed into the application by the system.
    //
    // Returns:
    // A Dictionary with string Keys and Values.
    //
    // If a key is found without a matching value, Dictionary.Value is set to the key
    //  (including the dashes).
    // If a value is found without a matching key, Dictionary.Key is set to "--NoKeyN",
    //  where "N" represents sequential numbers.
    public static Dictionary<string,string> Parse(string[] args)
    {
      var parsedArgs = new Dictionary<string,string>();
      int i = 0, n = 0;
      while(i < args.Length)
      {
        // If the first argument in this iteration starts with a dash it's an option.
        if(args[i].StartsWith("-"))
        {
          var key = args[i++];
          var value = key;

          // Check to see if there's a value that goes with this option?
          if((i < args.Length) && (!args[i].StartsWith("-"))) value = args[i++];
          parsedArgs.Add(key, value);
        }

        // If the first argument in this iteration doesn't start with a dash, it's a value
        else
        {
          parsedArgs.Add("--NoKey" + n.ToString(), args[i++]);
          n++;
        }
      }

      return parsedArgs;
    }

    //
    // Method to get an argument from the parsed command-line arguments
    //
    // Parameters:
    // - parsedArgs: The Dictionary object returned from the Parse() method (shown above).
    // - defaultValue: The default string to return if the specified key isn't in parsedArgs.
    // - keys: An array of keys to look for in parsedArgs.
    public static string GetArgument(
      Dictionary<string,string> parsedArgs, string defaultReturn, params string[] keys)
    {
      string retval = null;
      foreach(var key in keys)
        if(parsedArgs.TryGetValue(key, out retval)) break;
      return retval ?? defaultReturn;
    }

    //
    // Method to exit the application with an error.
    public static void ErrorExit(string msg, int code=1)
    {
      Console.WriteLine("\nError");
      Console.WriteLine(msg);
      Environment.Exit(code);
    }
  }

}
```

## Ulteriori considerazioni
<a name="kms-s3-additional"></a>
+ Puoi controllare i risultati di questo esempio. Per farlo, vai alla [console Amazon S3](https://console.aws.amazon.com/s3) e apri il bucket che hai fornito all'applicazione. Quindi trova il nuovo oggetto, scaricalo e aprilo in un editor di testo.
+ La classe [AmazonS3 EncryptionClient V2](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3EncryptionClientV2.html) implementa la stessa interfaccia della classe standard. `AmazonS3Client` Ciò semplifica il trasferimento del codice alla `AmazonS3EncryptionClientV2` classe in modo che la crittografia e la decrittografia avvengano automaticamente e in modo trasparente nel client.
+ Uno dei vantaggi dell'utilizzo di una AWS KMS chiave come chiave principale è che non è necessario archiviare e gestire le proprie chiavi master; questa operazione viene eseguita da. AWS Un secondo vantaggio è che la `AmazonS3EncryptionClientV2` classe di AWS SDK per .NET è interoperabile con la `AmazonS3EncryptionClientV2` classe di. AWS SDK per Java Ciò significa che è possibile crittografare con AWS SDK per Java e decrittografare con, e viceversa. AWS SDK per .NET
**Nota**  
La `AmazonS3EncryptionClientV2` classe di AWS SDK per .NET supporta le chiavi master KMS solo se eseguita in modalità metadati. La modalità del file di istruzioni della `AmazonS3EncryptionClientV2` classe di AWS SDK per .NET è incompatibile con la `AmazonS3EncryptionClientV2` classe di. AWS SDK per Java
+ Per ulteriori informazioni sulla crittografia lato client con la `AmazonS3EncryptionClientV2` classe e su come funziona la crittografia a busta, consulta [Client Side Data Encryption with e Amazon AWS SDK per .NET S3](https://aws.amazon.com/blogs/developer/client-side-data-encryption-with-aws-sdk-for-net-and-amazon-s3/).