Tous les produits
Search
Centre de documentation

Object Storage Service:Chiffrement côté serveur (SDK PHP V2)

Dernière mise à jour :Aug 18, 2026

Object Storage Service (OSS) propose un chiffrement côté serveur pour les données chargées. Lors du chargement, OSS chiffre et stocke les données. Au moment du téléchargement, OSS les déchiffre automatiquement et renvoie les données d'origine. L'en-tête de réponse HTTP indique que les données ont été chiffrées sur le serveur.

Remarques

  • Avant de configurer le chiffrement côté serveur, assurez-vous de bien comprendre cette fonctionnalité. Pour plus d'informations, consultez la rubrique Chiffrement côté serveur.

  • L'exemple de code présenté dans cette rubrique utilise un endpoint public de la région Chine (Hangzhou) (cn-hangzhou) à titre d'exemple. Si vous souhaitez accéder à OSS depuis d'autres produits Alibaba Cloud situés dans la même région, vous devez utiliser un endpoint de réseau interne. Pour plus d'informations sur les régions et les endpoints pris en charge par OSS, consultez la rubrique Régions et endpoints.

  • Pour configurer le chiffrement du bucket, vous devez disposer de l'autorisation oss:PutBucketEncryption. Pour récupérer la configuration de chiffrement du bucket, vous devez disposer de l'autorisation oss:GetBucketEncryption. Pour supprimer la configuration de chiffrement du bucket, vous devez disposer de l'autorisation oss:DeleteBucketEncryption. Pour plus d'informations, consultez la rubrique Attacher une politique personnalisée à un utilisateur RAM.

Exemples

Configurer le chiffrement du bucket

Utilisez le code suivant pour définir la méthode de chiffrement par défaut d'un bucket. Une fois la configuration appliquée, tous les objets chargés dans le bucket sans méthode de chiffrement spécifiée sont chiffrés à l'aide de la méthode de chiffrement par défaut du 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 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.
);

Récupérer la configuration de chiffrement du bucket

Utilisez le code suivant pour récupérer la configuration de chiffrement du 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.
);

Supprimer la configuration de chiffrement du bucket

Utilisez le code suivant pour supprimer la configuration de chiffrement du 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.
);

Références

  • Pour obtenir l'exemple de code complet relatif au chiffrement côté serveur, consultez les rubriques put_bucket_encryption, get_bucket_encryption et delete_bucket_encryption.

  • Pour plus d'informations sur l'opération API permettant de configurer le chiffrement côté serveur, consultez la rubrique PutBucketEncryption.

  • Pour plus d'informations sur l'opération API permettant de récupérer la configuration de chiffrement côté serveur, consultez la rubrique GetBucketEncryption.

  • Pour plus d'informations sur l'opération API permettant de supprimer la configuration de chiffrement côté serveur, consultez la rubrique DeleteBucketEncryption.