Todos os produtos
Search
Central de documentação

Object Storage Service:Criptografia no lado do servidor (PHP SDK V2)

Última atualização: Jul 03, 2026

O Object Storage Service (OSS) oferece criptografia no lado do servidor para dados enviados. Durante o upload, o OSS criptografa e armazena os dados. No download, o OSS descriptografa automaticamente o conteúdo e retorna os dados originais. O cabeçalho de resposta HTTP indica que a criptografia ocorreu no servidor.

Observações de uso

  • Antes de configurar a criptografia no lado do servidor, certifique-se de compreender esse recurso. Para mais informações, consulte Criptografia no lado do servidor.

  • O código de exemplo neste tópico usa um endpoint público na região China (Hangzhou) (cn-hangzhou) como referência. Para acessar o OSS a partir de outros produtos da Alibaba Cloud na mesma região, use um endpoint de rede interna. Para mais detalhes sobre as regiões e endpoints compatíveis com o OSS, consulte Regiões e endpoints.

  • A configuração da criptografia do bucket exige a permissão oss:PutBucketEncryption. A obtenção da configuração de criptografia do bucket exige a permissão oss:GetBucketEncryption. A exclusão da configuração de criptografia do bucket exige a permissão oss:DeleteBucketEncryption. Para mais informações, consulte Anexar uma política personalizada a um usuário RAM.

Exemplos

Configure a criptografia do bucket

Use o código abaixo para definir o método de criptografia padrão de um bucket. Após a configuração, todos os objetos enviados ao bucket sem um método de criptografia específico serão criptografados com o método padrão definido.

<?php

// Import the autoloader file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define command line argument descriptions.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located', 'required' => True], // Required. The region where the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // Optional. The domain name that other services can use to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // Required. The name of the bucket.
];

// Generate a long options list to parse command line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // A colon (:) after each parameter indicates that a value is required.
}, array_keys($optsdesc));

// Parse the command line arguments.
$options = getopt("", $longopts); 

// Check if required arguments are missing.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Prompt the user that a required argument is missing.
        exit(1); 
    }
}

// Get the command line argument values.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.

// Load credentials (AccessKeyId and AccessKeySecret) from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();

// Set the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);

// Set the region.
$cfg->setRegion($region);

// If an endpoint is provided, set the endpoint.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Create a request object to set the bucket encryption configuration. Use the KMS encryption algorithm and specify SM4 as the data encryption method.
$request = new Oss\Models\PutBucketEncryptionRequest(
    bucket: $bucket, 
    serverSideEncryptionRule: new Oss\Models\ServerSideEncryptionRule(
        applyServerSideEncryptionByDefault: new Oss\Models\ApplyServerSideEncryptionByDefault(
            sseAlgorithm: 'KMS', // Use the KMS encryption algorithm.
            kmsDataEncryption: 'SM4' // The data encryption method is SM4.
    ))
);

// Call the putBucketEncryption method to set the encryption configuration for the bucket.
$result = $client->putBucketEncryption($request);

// Print the response.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
    'request id:' . $result->requestId // The unique identifier of the request.
);

Obtenha a configuração de criptografia do bucket

Use o código a seguir para obter a configuração de criptografia do bucket.

<?php

// Import the autoloader file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define command line argument descriptions.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located', 'required' => True], // Required. The region where the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // Optional. The domain name that other services can use to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // Required. The name of the bucket.
];

// Generate a long options list to parse command line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // A colon (:) after each parameter indicates that a value is required.
}, array_keys($optsdesc));

// Parse the command line arguments.
$options = getopt("", $longopts); 

// Check if required arguments are missing.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Prompt the user that a required argument is missing.
        exit(1); 
    }
}

// Get the command line argument values.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.

// Load credentials (AccessKeyId and AccessKeySecret) from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();

// Set the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);

// Set the region.
$cfg->setRegion($region);

// If an endpoint is provided, set the endpoint.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Create a request object to get the bucket encryption configuration.
$request = new Oss\Models\GetBucketEncryptionRequest(bucket: $bucket);

// Call the getBucketEncryption method to get the encryption configuration of the bucket.
$result = $client->getBucketEncryption($request);

// Print the response.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
    'request id:' . $result->requestId . PHP_EOL . // The unique identifier of the request.
    'encryption:' . var_export($result->serverSideEncryptionRule, true) // The encryption configuration.
);

Exclua a configuração de criptografia do bucket

Use o código abaixo para excluir a configuração de criptografia do bucket.

<?php

// Import the autoloader file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define command line argument descriptions.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located', 'required' => True], // Required. The region where the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // Optional. The domain name that other services can use to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // Required. The name of the bucket.
];

// Generate a long options list to parse command line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // A colon (:) after each parameter indicates that a value is required.
}, array_keys($optsdesc));

// Parse the command line arguments.
$options = getopt("", $longopts); 

// Check if required arguments are missing.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Prompt the user that a required argument is missing.
        exit(1); 
    }
}

// Get the command line argument values.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.

// Load credentials (AccessKeyId and AccessKeySecret) from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();

// Set the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);

// Set the region.
$cfg->setRegion($region);

// If an endpoint is provided, set the endpoint.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Create a request object to delete the bucket encryption configuration.
$request = new Oss\Models\DeleteBucketEncryptionRequest(bucket: $bucket);

// Call the deleteBucketEncryption method to delete the encryption configuration of the bucket.
$result = $client->deleteBucketEncryption($request);

// Print the response.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
    'request id:' . $result->requestId // The unique identifier of the request.
);

Referências