

# Usar `PutBucketEncryption` com o AWS SDK ou a CLI
<a name="s3_example_s3_PutBucketEncryption_section"></a>

Os exemplos de código a seguir mostram como usar o `PutBucketEncryption`.

Exemplos de ações são trechos de código de programas maiores e devem ser executados em contexto. É possível ver essa ação no contexto no seguinte exemplo de código: 
+  [Introdução ao armazenamento de objetos](s3_example_s3_GettingStarted_section.md) 

------
#### [ .NET ]

**SDK para .NET**  
 Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no [AWSCode Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3/PutBucketEncryption#code-examples). 

```
    /// <summary>
    /// Set the bucket server side encryption to use AWSKMS with a customer-managed key id.
    /// </summary>
    /// <param name="bucketName">Name of the bucket.</param>
    /// <param name="kmsKeyId">The Id of the KMS Key.</param>
    /// <returns>True if successful.</returns>
    public static async Task<bool> SetBucketServerSideEncryption(string bucketName, string kmsKeyId)
    {
        var serverSideEncryptionByDefault = new ServerSideEncryptionConfiguration
        {
            ServerSideEncryptionRules = new List<ServerSideEncryptionRule>
            {
                new ServerSideEncryptionRule
                {
                    ServerSideEncryptionByDefault = new ServerSideEncryptionByDefault
                    {
                        ServerSideEncryptionAlgorithm = ServerSideEncryptionMethod.AWSKMS,
                        ServerSideEncryptionKeyManagementServiceKeyId = kmsKeyId
                    }
                }
            }
        };
        try
        {
            var encryptionResponse = await _s3Client.PutBucketEncryptionAsync(new PutBucketEncryptionRequest
            {
                BucketName = bucketName,
                ServerSideEncryptionConfiguration = serverSideEncryptionByDefault,
            });
            
            return encryptionResponse.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine(ex.ErrorCode == "AccessDenied"
                ? $"This account does not have permission to set encryption on {bucketName}, please try again."
                : $"Unable to set bucket encryption for bucket {bucketName}, {ex.Message}");
        }
        return false;
    }
```
+  Para ter detalhes da API, consulte [PutBucketEncryption](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/PutBucketEncryption) na *Referência da API do AWS SDK para .NET*. 

------
#### [ CLI ]

**AWS CLI**  
**Para configurar a criptografia do lado do servidor para um bucket**  
O exemplo `put-bucket-encryption` a seguir define a criptografia AES256 como padrão para o bucket especificado.  

```
aws s3api put-bucket-encryption \
    --bucket {{amzn-s3-demo-bucket}} \
    --server-side-encryption-configuration '{{{"Rules": [{"ApplyServerSideEncryptionByDefault": {"SSEAlgorithm": "AES256"}}]}}}'
```
Este comando não produz saída.  
+  Consulte detalhes da API em [PutBucketEncryption](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-encryption.html) na *Referência de comandos da AWS CLI*. 

------
#### [ PowerShell ]

**Ferramentas para PowerShell V4**  
**Exemplo 1: este comando habilita a criptografia padrão do lado do servidor AES256 com chaves gerenciadas do Amazon S3 (SSE-S3) no bucket em questão. **  

```
$Encryptionconfig = @{ServerSideEncryptionByDefault = @{ServerSideEncryptionAlgorithm = "AES256"}}
Set-S3BucketEncryption -BucketName 'amzn-s3-demo-bucket' -ServerSideEncryptionConfiguration_ServerSideEncryptionRule $Encryptionconfig
```
+  Consulte detalhes da API em [PutBucketEncryption](https://docs.aws.amazon.com/powershell/v4/reference) na *Referência de cmdlet do Ferramentas da AWS para PowerShell (V4)*. 

**Ferramentas para PowerShell V5**  
**Exemplo 1: este comando habilita a criptografia padrão do lado do servidor AES256 com chaves gerenciadas do Amazon S3 (SSE-S3) no bucket em questão. **  

```
$Encryptionconfig = @{ServerSideEncryptionByDefault = @{ServerSideEncryptionAlgorithm = "AES256"}}
Set-S3BucketEncryption -BucketName 'amzn-s3-demo-bucket' -ServerSideEncryptionConfiguration_ServerSideEncryptionRule $Encryptionconfig
```
+  Consulte detalhes da API em [PutBucketEncryption](https://docs.aws.amazon.com/powershell/v5/reference) na *Referência de cmdlet do Ferramentas da AWS para PowerShell (V5)*. 

------

Para ver uma lista completa dos guias de desenvolvedor e exemplos de código do SDK da AWS, consulte [Desenvolvimento com o Amazon S3 usando AWS SDKs](sdk-general-information-section.md). Este tópico também inclui informações sobre como começar e detalhes sobre versões anteriores do SDK.