O Object Storage Service (OSS) criptografa os dados enviados no servidor, recurso conhecido como criptografia do lado do servidor. Ao fazer upload de dados para o OSS, o serviço criptografa o conteúdo e o armazena de forma persistente. Durante o download, o OSS descriptografa os dados e retorna o conteúdo original. Além disso, o sistema adiciona um cabeçalho à resposta para indicar que a criptografia ocorreu no servidor.
Observações
Antes de configurar a criptografia do lado do servidor, familiarize-se com esse recurso. Para mais informações, consulte Criptografia do lado do servidor.
Este tópico utiliza o endpoint público da região China (Hangzhou). Caso precise acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, utilize um endpoint interno. Para mais detalhes sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
Os exemplos abaixo demonstram a criação de uma instância OSSClient com um endpoint do OSS. Para outras configurações, como uso de domínio personalizado ou autenticação via credenciais do Security Token Service (STS), consulte Inicialização (C# SDK V1).
Para configurar a criptografia do lado do servidor em um bucket, você precisa da permissão
oss:PutBucketEncryption. Para consultar as configurações de criptografia do lado do servidor de um bucket, você precisa da permissãooss:GetBucketEncryption. Para excluir essas configurações, você precisa da permissãooss:DeleteBucketEncryption. Para mais informações, consulte Conceder uma política personalizada.
Configurar a criptografia do lado do servidor para um bucket
O código de exemplo a seguir mostra como definir um método de criptografia padrão para um bucket. Após essa configuração, todos os objetos enviados ao bucket sem um método de criptografia específico serão protegidos automaticamente pelo método padrão.
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify parameters as required.
var conf = new ClientConfiguration();
// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Configure server-side encryption for the bucket.
var request = new SetBucketEncryptionRequest(bucketName, "KMS", null);
client.SetBucketEncryption(request);
Console.WriteLine("Set bucket:{0} Encryption succeeded ", bucketName);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}
Consultar as configurações de criptografia do lado do servidor de um bucket
O exemplo de código abaixo ilustra como obter as configurações de criptografia do lado do servidor de um bucket:
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify parameters as required.
var conf = new ClientConfiguration();
// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Query the server-side encryption configurations of the bucket.
var result = client.GetBucketEncryption(bucketName);
Console.WriteLine("Get bucket:{0} Encryption succeeded ", bucketName);
Console.WriteLine("SSEAlgorithm: {0}", result.SSEAlgorithm);
Console.WriteLine("KMSMasterKeyID: {0}", result.KMSMasterKeyID);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}
Excluir as configurações de criptografia do lado do servidor de um bucket
Utilize o código a seguir para remover as configurações de criptografia do lado do servidor de um bucket:
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify parameters as required.
var conf = new ClientConfiguration();
// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Delete the server-side encryption configurations of the bucket.
client.DeleteBucketEncryption(bucketName);
Console.WriteLine("Delete bucket:{0} Encryption succeeded ", bucketName);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}
Referências
Para detalhes sobre a operação de API usada para configurar a criptografia do lado do servidor, consulte PutBucketEncryption.
Saiba mais sobre a operação de API para consulta das configurações de criptografia do lado do servidor em GetBucketEncryption.
A documentação da operação de API para exclusão das configurações de criptografia do lado do servidor está disponível em DeleteBucketEncryption.