All Products
Search
Document Center

Object Storage Service:Server-side encryption

Last Updated:Oct 10, 2025

When you upload an object to a bucket with server-side encryption enabled, Object Storage Service (OSS) encrypts the object before storing it. When you call the GetObject operation to download the object, OSS automatically decrypts the object and returns it. The response includes the x-oss-server-side-encryption header to indicate that the object was encrypted on the server side.

Note

For more information about the x-oss-server-side-encryption response header, see Response headers.

Scenarios

OSS uses server-side encryption to provide data-at-rest protection. This feature is suitable for scenarios with high security or compliance requirements for data storage, such as storing deep learning sample files and online collaborative documents.

Encryption methods

OSS provides two server-side encryption methods for different scenarios. You can select a method based on your requirements.

Encryption method

Description

Scenarios

Notes

Billing

Server-side encryption with keys managed by Key Management Service (SSE-KMS)

Use the default customer master key (CMK) managed by Key Management Service (KMS) or a specified CMK to encrypt and decrypt data. Data is encrypted and decrypted without being sent over the network to the KMS server.

This method is suitable when you need to use self-managed or user-specified keys to meet security and compliance requirements.

  • The key used to encrypt an object is also encrypted and written to the object's metadata.

  • Server-side encryption with KMS-managed keys encrypts only object data, not object metadata.

You are charged when you call API operations to encrypt or decrypt data using CMKs stored in KMS. For more information, see Billing of KMS.

Server-side encryption with OSS-managed keys (SSE-OSS)

Use a key that is fully managed by OSS to encrypt each object. For enhanced security, OSS also uses a master key to encrypt the data encryption key itself.

This method is suitable when only basic encryption capabilities are required and you do not need to manage keys.

None.

Free of charge.

Notes

  • To upload, download, or access objects in a bucket that is encrypted using SSE-KMS, you must have permissions to use the specified CMK ID, and the request must not be anonymous. Otherwise, the request fails and the This request is forbidden by kms error is returned.

  • Objects in a bucket that are retrieved using mirroring-based back-to-origin rules are not encrypted by default.

  • Enabling or changing the encryption method for a bucket does not affect the encryption configuration of existing objects in the bucket.

  • An object can be encrypted by only one server-side encryption method at a time.

  • If you configure encryption for a bucket, you can still configure a separate encryption method for an object when you upload or copy it. The encryption method configured for the object takes precedence. For more information, see PutObject.

Permissions

The following list describes the permissions that a Resource Access Management (RAM) user needs to use server-side encryption in different scenarios.

Note

For more information, see Grant custom permissions to a RAM user.

  • Set the encryption method for a bucket

    • Permissions to manage the target bucket.

    • The PutBucketEncryption and GetBucketEncryption permissions.

    • If you set the encryption method to SSE-KMS and specify a CMK ID, you also need the ListKeys, Listalias, ListAliasesByKeyId, and DescribeKey permissions. The following is an example RAM policy:

      {
        "Version": "1",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": [
              "kms:List*",
              "kms:DescribeKey"    
            ],
            "Resource": [
              "acs:kms:*:141661496593****:*" // Allows the use of all KMS keys under this Alibaba Cloud account ID. To allow only a specific CMK, enter its CMK ID.
            ]
          }
        ]
      }
  • Upload an object to an encrypted bucket

    • Permissions to upload objects to the target bucket.

    • If you set the encryption method to KMS and specify a CMK ID, you also need the ListKeys, ListAliases, ListAliasesByKeyId, DescribeKey, GenerateDataKey, and Decrypt permissions. The following is an example RAM policy:

      {
        "Version": "1",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": [
              "kms:List*",
              "kms:DescribeKey",
              "kms:GenerateDataKey",
              "kms:Decrypt"
            ],
            "Resource": [
              "acs:kms:*:141661496593****:*"// Allows the use of all KMS keys under this Alibaba Cloud account ID. To allow only a specific CMK, enter its CMK ID.
            ]
          }
        ]
      }
  • Download an object from an encrypted bucket

    • Permissions to access objects in the target bucket.

    • If the encryption method is KMS and a CMK ID is specified, you also need the Decrypt permission. The following is an example RAM policy:

      {
        "Version": "1",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": [
              "kms:Decrypt"
            ],
            "Resource": [
              "acs:kms:*:141661496593****:*"// Grants decryption permissions for all KMS keys under this Alibaba Cloud account ID. To grant decryption permissions for a specific KMS key, enter its CMK ID.
            ]
          }
        ]
      }

Methods

Important
  • If you purchased the KMS key rotation value-added service, server-side encryption supports key rotation for KMS keys. After you enable key rotation, the new key is used to encrypt only new objects. The encryption key for existing objects remains unchanged.

  • If you update a KMS encryption key through OSS, the new key applies only to objects that are written after the update. Existing objects that were written before the key update are still encrypted with the old key. Therefore, do not delete the old key after an update. Otherwise, you cannot access the existing objects.

Use the OSS console

Method 1: Enable server-side encryption for a bucket

Enable server-side encryption when you create a bucket

  1. Log on to the OSS console.

  2. Click Buckets, and then click Create Bucket.

  3. In the Create Bucket panel, configure the parameters as described in the following table.

    The following table describes the parameters in the Server-side Encryption section.

    Parameter

    Description

    Encryption Method

    Select an encryption method for objects. Valid values:

    • None: Server-side encryption is disabled.

    • OSS-Managed: Use OSS-managed keys for encryption. OSS uses a different key to encrypt each object. For extra protection, OSS uses a master key to encrypt the data encryption keys.

    • KMS: Use the default KMS-managed CMK or a specified CMK ID for encryption and decryption.

      Before you use the KMS encryption method, you must activate KMS. For more information, see Activate KMS.

    Encryption Algorithm

    Only the AES256 encryption algorithm is supported.

    Encryption Key

    This parameter is required only when you set Encryption Method to KMS.

    Select an encryption key. The key is in the format of <alias>(CMK ID). In this format, <alias> is the alias of the CMK and CMK ID is the ID of the CMK. Valid values:

    • alias/acs/oss(CMK ID): If you select this option, OSS uses the default service key to encrypt data in the bucket and automatically decrypts objects when they are downloaded.

    • alias/<cmkname>(CMK ID): If you select this option, OSS uses the specified service key to encrypt data in the bucket. The CMK ID of the encrypted object is recorded in the object's metadata. Users with decryption permissions can automatically decrypt the object when they download it. In this format, <cmkname> is the optional identifier for the CMK that you configured when you created the key.

      Before you use a specified CMK ID, you must create a normal or external key in the same region as the bucket in the KMS console. For more information, see Create a key.

    For more information, see Create buckets.

  4. Click OK.

Enable server-side encryption for an existing bucket

  1. Log on to the OSS console.

  2. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

  3. In the navigation pane on the left, choose Data Security > Server-side Encryption.

  4. On the Server-side Encryption page, click Settings and configure the parameters as described in the following table.

    Parameter

    Description

    Encryption Method

    Select an encryption method for objects. Valid values:

    • None: Server-side encryption is disabled.

    • OSS-Managed: Use OSS-managed keys for encryption. OSS uses a different key to encrypt each object. For extra protection, OSS uses a master key to encrypt the data encryption keys.

    • KMS: Use the default KMS-managed CMK or a specified CMK ID for encryption and decryption.

      Before you use the KMS encryption method, you must activate KMS. For more information, see Activate KMS.

    Encryption Algorithm

    Only the AES256 encryption algorithm is supported.

    Encryption Key

    This parameter is required only when you set Encryption Method to KMS.

    Select an encryption key. The key is in the format of <alias>(CMK ID). In this format, <alias> is the alias of the CMK and CMK ID is the ID of the CMK. Valid values:

    • OSS creates a service key for you by default: If you select this option, OSS generates a default service key to encrypt data in this bucket. When you download an object from the bucket, OSS automatically decrypts the object. The default service key created by OSS is in the format of alias/acs/oss (CMK ID). You can view this service key in the KMS console.

      Note

      Before you can view this service key in the KMS console, you must upload at least one file to the target bucket. This ensures that the encryption key is created and associated with your OSS service.

    • alias/<cmkname>(CMK ID): If you select this option, OSS uses the specified service key to encrypt data in the bucket. The CMK ID of the encrypted object is recorded in the object's metadata. Users with decryption permissions can automatically decrypt the object when they download it. In this format, <cmkname> is the optional identifier for the CMK that you configured when you created the key.

      Before you use a specified CMK ID, you must create a normal or external key in the same region as the bucket in the KMS console. For more information, see Create a key.

  5. Click Save.

Method 2: Set server-side encryption when you upload a file

For more information, see Simple upload.

Use Alibaba Cloud SDKs

Method 1: Enable server-side encryption for a bucket

You can use an SDK to enable server-side encryption for an existing bucket. You cannot enable server-side encryption when you create a bucket. The following code provides examples of how to enable server-side encryption for an existing bucket using common SDKs. For more information about how to enable server-side encryption for an existing bucket using other SDKs, see SDK overview.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // Specify the endpoint of the region. In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 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. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String 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. 
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // Call the shutdown method to release resources when the OSSClient is no longer in use. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Set the encryption algorithm to SM4 for the bucket. If AES-256 is used, replace SSEAlgorithm.SM4 with SSEAlgorithm.AES256. 
            ServerSideEncryptionByDefault applyServerSideEncryptionByDefault = new ServerSideEncryptionByDefault(SSEAlgorithm.SM4);
            ServerSideEncryptionConfiguration sseConfig = new ServerSideEncryptionConfiguration();
            sseConfig.setApplyServerSideEncryptionByDefault(applyServerSideEncryptionByDefault);
            SetBucketEncryptionRequest request = new SetBucketEncryptionRequest(bucketName, sseConfig);
            ossClient.setBucketEncryption(request);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
<?php

// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command line parameters.
$optsdesc = [
    "region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket.
];

// Generate a long options list to parse the command line parameters.
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));

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

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Specify that the required parameters are not configured.
        exit(1); 
    }
}

// Obtain the values of the command line parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.

// Use environment variables to load the AccessKey ID and AccessKey secret.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

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

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

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

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

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

// Create a PutBucketEncryptionRequest object, use the Key Management Service (KMS) encryption method, and set the encryption algorithm to SM4.
$request = new Oss\Models\PutBucketEncryptionRequest(
    bucket: $bucket, 
    serverSideEncryptionRule: new Oss\Models\ServerSideEncryptionRule(
        applyServerSideEncryptionByDefault: new Oss\Models\ApplyServerSideEncryptionByDefault(
            sseAlgorithm: 'KMS', //Use the KMS encryption method.
            kmsDataEncryption: 'SM4' // Set the encryption algorithm to SM4.
    ))
);

// Use the putBucketEncryption method to configure the server-side encryption configurations for the bucket.
$result = $client->putBucketEncryption($request);

// Display the returned result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The returned HTTP status code.
    'request id:' . $result->requestId // The request ID of the request, which is the unique identifier of the request.
);
const OSS = require("ali-oss");

const client = new OSS({
  // 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 oss-cn-hangzhou. 
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the name of the bucket. 
  bucket: 'yourbucketname'
});

async function putBucketEncryption() {
  try {
    // Configure an encryption method for the bucket.     

    const result = await client.putBucketEncryption("bucket-name", {
      SSEAlgorithm: "AES256", // In this example, the AES-256 encryption algorithm is used. To use KMS for encryption, you must specify KMSMasterKeyID. 
      // KMSMasterKeyID: "yourKMSMasterKeyId". Specify the CMK ID. This parameter is available and required when SSEAlgorithm is set to KMS and a specific CMK is used for encryption. In other cases, leave this parameter empty. 
    });
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

putBucketEncryption();
import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser to receive user-entered parameters.
parser = argparse.ArgumentParser(description="put bucket encryption sample")

# Add the --region command-line argument, which specifies the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# Add the --bucket command-line argument, which specifies the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# Add the --endpoint command-line argument, which specifies the domain name that other services use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

# Add the --sse_algorithm command-line argument, which specifies the default server-side encryption method. The default value is 'KMS'.
# Valid values: KMS (encryption using KMS), AES256 (encryption using AES-256), and SM4 (encryption using the Chinese cryptographic algorithm SM4).
parser.add_argument('--sse_algorithm', help='The default server-side encryption method. Valid values: KMS, AES256, and SM4.', default='KMS')

# Add the --kms_master_key_id command-line argument, which specifies the ID of the master key when SSEAlgorithm is set to KMS and a specified CMK is used.
# If you do not use a specified CMK, leave this parameter empty.
parser.add_argument('--kms_master_key_id', help='The CMK ID that is specified when SSEAlgorithm is set to KMS and a specified CMK is used for encryption. In other cases, leave this parameter empty.', default='')

# Add the --kms_data_encryption command-line argument, which specifies the algorithm used for object encryption.
# The default value is 'SM4'. This parameter is valid only when SSEAlgorithm is set to KMS.
parser.add_argument('--kms_data_encryption', help='The algorithm that is used to encrypt objects. If this parameter is not specified, objects are encrypted using AES256. This parameter is valid only when SSEAlgorithm is set to KMS. Valid value: SM4', default='SM4')

def main():
    # Parse command-line arguments.
    args = parser.parse_args()

    # Load credentials (AccessKeyId and AccessKeySecret) from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK.
    cfg = oss.config.load_default()

    # Set the credential provider.
    cfg.credentials_provider = credentials_provider

    # Set the region where the bucket is located.
    cfg.region = args.region

    # If the user provides a custom endpoint, set it in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Initialize the OSS client using the configuration object.
    client = oss.Client(cfg)

    # Call the put_bucket_encryption method to set the encryption configuration for the bucket.
    result = client.put_bucket_encryption(
        oss.PutBucketEncryptionRequest(
            bucket=args.bucket,  # Specify the name of the destination bucket.
            server_side_encryption_rule=oss.ServerSideEncryptionRule(
                apply_server_side_encryption_by_default=oss.ApplyServerSideEncryptionByDefault(
                    kms_master_key_id=args.kms_master_key_id,  # The master key ID. This parameter is valid only when SSEAlgorithm is set to KMS.
                    kms_data_encryption=args.kms_data_encryption,  # The object encryption algorithm. This parameter is valid only when SSEAlgorithm is set to KMS.
                    sse_algorithm=args.sse_algorithm,  # The server-side encryption algorithm, such as KMS, AES256, or SM4.
                ),
            ),
        )
    )

    # Print the status code and request ID of the operation result.
    print(f'status code: {result.status_code}, '  # The HTTP status code, which indicates whether the request is successful.
          f'request id: {result.request_id}')     # The request ID, which is used to track request logs and for debugging.


if __name__ == "__main__":
    # The program entry point. Call the main function to execute the logic.
    main()
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);
}
package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// 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. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Error creating credentials provider: %v", err)
	}

	// Create an OSSClient instance. 
	// 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. Specify your actual endpoint. 
	// 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. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Error creating OSS client: %v", err)
	}

	// Initialize an encryption rule. In this example, the AES-256 encryption algorithm is used. 
	config := oss.ServerEncryptionRule{
		SSEDefault: oss.SSEDefaultRule{
			SSEAlgorithm: "AES256",
		},
	}

	// Configures encryption rules for the OSS bucket.
	err = client.SetBucketEncryption("yourBucketName", config)
	if err != nil {
		log.Fatalf("Error setting bucket encryption: %v", err)
	}

	log.Println("Bucket encryption set successfully")
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize information about the account that is used to access OSS. */
            
    /* Specify the endpoint of the region in which the bucket is located. Specify the endpoint of the region in which the bucket is located. */
    std::string Endpoint = "yourEndpoint";
    /* 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.*/
    std::string Region = "yourRegion";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize resources, such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* 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. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    SetBucketEncryptionRequest setrequest(BucketName);
    setrequest.setSSEAlgorithm(SSEAlgorithm::KMS);
    /* Configure server-side encryption based on KMS. */
    auto outcome = client.SetBucketEncryption(setrequest);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "SetBucketEncryption fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release resources, such as network resources. */
    ShutdownSdk();
    return 0;
}

Method 2: Set server-side encryption when you upload a file

The following code provides examples of how to set server-side encryption when you upload an object using common SDKs. For more information about how to set server-side encryption when you upload an object using other SDKs, see SDK overview.

Java

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.model.ObjectMetadata;
import java.io.File;

public class Put {
    public static void main(String[] args) throws Exception {
        // The endpoint is set to China (Hangzhou) in this example. Set it to your actual region.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the region that corresponds to the endpoint, for example, cn-hangzhou.
        String region = "cn-hangzhou";
        // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name, for example, examplebucket.
        String bucketName = "examplebucket";
        // Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt.
        String objectName = "exampledir/exampleobject.txt";
        // Specify the full path of the local file, for example, D:\\localpath\\examplefile.txt.
        // If you do not specify a local path, the file is uploaded from the local path that corresponds to the project to which the sample program belongs.
        String filePath= "D:\\localpath\\examplefile.txt";
        
        // Create an OSSClient instance.
        // When the OSSClient instance is no longer used, call the shutdown method to release resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // Explicitly declare the use of the V4 signature algorithm.
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();
                
        try {
            // Create an ObjectMetadata object and set the server-side encryption method to AES256.
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setHeader(OSSHeaders.OSS_SERVER_SIDE_ENCRYPTION, "AES256");

            // Create a PutObjectRequest object.
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));
            putObjectRequest.setMetadata(metadata); 

            // Upload the file.
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

PHP

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\Core\OssException;


// Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// Set yourEndpoint to the endpoint of the region where the bucket is located. For example, for China (Hangzhou), set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the bucket name, for example, examplebucket.
$bucket= "examplebucket";
// Specify the full path of the object, for example, exampledir/exampleobject.txt. The full path cannot contain the bucket name.
$object = "exampledir/exampleobject.txt";
// Specify the full path of the local file, for example, D:\\localpath\\examplefile.txt. If you do not specify a local path, the file is uploaded from the local path that corresponds to the project to which the sample program belongs.
$filePath = "D:\\localpath\\examplefile.txt";

try{
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
    );
    $ossClient = new OssClient($config);

    $options[OssClient::OSS_HEADERS] = array(
         // Set the server-side encryption method to AES256.
        "x-oss-server-side-encryption"=>"AES256",
    );
    // Call the uploadFile method to upload the file and pass the UploadOptions object.
    $ossClient->uploadFile($bucket, $object, $filePath, $options);
} catch(OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . "OK" . "\n");

Node.js

const OSS = require("ali-oss");
const path = require("path");

const client = new OSS({
  // Set yourregion to the region where the bucket is located. For example, for China (Hangzhou), set the region to oss-cn-hangzhou.
  region: "oss-cn-hangzhou",
  // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the bucket name.
  bucket: "examplebucket",
});

const headers = {
  // Set the server-side encryption method to AES256.
  "x-oss-server-side-encryption": "AES256",
};

async function put() {
  try {
    const result = await client.put(
      // Specify the full path of the object, for example, exampledir/exampleobject.txt. The full path cannot contain the bucket name.
      "exampledir/exampleobject.txt",
      // Specify the full path of the local file, for example, D:\\localpath\\examplefile.txt. If you do not specify a local path, the file is uploaded from the local path that corresponds to the project to which the sample program belongs.
      path.normalize("D:\\examplefile.jpg"),
      { headers }
    );
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

put();

Python

# -*- coding: utf-8 -*-
import oss2
import os
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())

# Set yourEndpoint to the endpoint of the region where the bucket is located. For example, for China (Hangzhou), set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'

# Specify the bucket name.
bucket_name = 'examplebucket0703'
bucket = oss2.Bucket(auth, endpoint, bucket_name)

# You must open the file in binary mode.
# Specify the full path of the local file. If you do not specify a local path, the file is uploaded from the local path that corresponds to the project to which the sample program belongs.
local_file_path = 'D:\\examplefile.jpg'
with open(local_file_path, 'rb') as fileobj:
    # The seek method specifies that the read and write operations start from the 1,000th byte. The upload starts from the 1,000th byte you specified and continues until the end of the file.
    fileobj.seek(1000, os.SEEK_SET)
    # The tell method returns the current position.
    current = fileobj.tell()

    # Set the server-side encryption method to AES256.
    headers = {
        'x-oss-server-side-encryption': 'AES256',
    }

    # Specify the full path of the object. The full path cannot contain the bucket name.
    object_key = 'exampledir/object1.jpg'
    bucket.put_object(object_key, fileobj, headers=headers)

Go

package main

import (
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"os"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, for China (Hangzhou), set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Set it to your actual region.
	client, err := oss.New("https://oss-cn-hangzhou.aliyuncs.com", "", "", oss.SetCredentialsProvider(&provider))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// Specify the bucket name, for example, examplebucket.
	bucket, err := client.Bucket("examplebucket")
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
  // Specify the full path of the object, for example, exampledir/exampleobject.txt. The full path cannot contain the bucket name.
  // Specify the full path of the local file, for example, D:\\localpath\\examplefile.txt. If you do not specify a local path, the file is uploaded from the local path that corresponds to the project to which the sample program belongs.
  // Set the server-side encryption method to AES256.
	err = bucket.PutObjectFromFile("D:\\localpath\\examplefile.txt", "D:\\examplefile.jpg", oss.ServerSideEncryption("AES256"))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
}

Use the ossutil command-line tool

Method 1: Enable server-side encryption for a bucket

You can use the ossutil command-line tool to enable server-side encryption for a bucket. To install ossutil, see Install ossutil.

The following command sets the server-side encryption method to AES256 for an existing bucket named examplebucket.

ossutil api put-bucket-encryption --bucket examplebucket --server-side-encryption-rule "{\"ApplyServerSideEncryptionByDefault\":{\"SSEAlgorithm\":\"AES256\"}}"

For more information, see put-bucket-encryption.

Method 2: Set server-side encryption when you upload a file

ossutil lets you specify the server-side encryption method for an object when you upload it. To install ossutil, see Install ossutil. The following command sets the server-side encryption method to AES256 when you upload an object.

ossutil cp examplefile.txt oss://examplebucket --metadata=x-oss-server-side-encryption:AES256

For more information, see cp.

Use KMS-managed keys for encryption and decryption

You can use a KMS-managed CMK to generate a data encryption key to encrypt data. The envelope encryption mechanism further prevents unauthorized data access. With KMS, you can focus on business functions such as data encryption, decryption, and digital signature verification without the high cost of ensuring the confidentiality, integrity, and availability of your keys.

The following figure shows the logic of the SSE-KMS encryption method.

image

When you use the SSE-KMS encryption method, you can use the following keys:

  • Use the default KMS key managed by OSS

    OSS uses the default KMS-managed CMK to generate different keys to encrypt different objects and automatically decrypts the objects when they are downloaded. When you use this method for the first time, OSS creates an OSS-managed CMK on the KMS platform.

    Configuration methods:

    • Configure the bucket encryption method

      Set the bucket encryption method to KMS but do not specify a CMK ID. Then, all objects uploaded to this bucket are encrypted.

    • You can configure the encryption method for the target object.

      When you upload an object or modify its metadata, include the x-oss-server-side-encryption parameter in the request and set its value to KMS. OSS then uses the default KMS-managed CMK and the AES256 encryption algorithm to encrypt the object. For more information, see PutObject.

  • Use Bring-Your-Own-Key (BYOK)

    After you use BYOK material to generate a CMK in the KMS console, OSS can use the specified KMS CMK to generate different keys to encrypt different objects. The CMK ID of the encrypted object is recorded in the object's metadata. Only users with decryption permissions can decrypt the object when they download it.

    There are two sources for BYOK material:

    • BYOK material provided by Alibaba Cloud: When you create a key on the KMS platform, select Alibaba Cloud KMS as the key material source.

    • Your own BYOK material: When you create a key on the KMS platform, select External as the key material source and import the external key material as needed. For more information, see Import key material.

    Configuration methods:

    • Configure the bucket encryption method

      Set the bucket encryption method to KMS and specify a CMK ID. Then, all objects uploaded to this bucket are encrypted.

    • You can configure the encryption method for the target object.

      When you upload an object or modify its metadata, set the x-oss-server-side-encryption parameter to KMS and the x-oss-server-side-encryption-key-id parameter to the specified CMK ID. In this case, OSS uses the specified KMS CMK and the AES256 encryption algorithm to encrypt the object. For more information, see PutObject.

Use OSS-managed keys for encryption and decryption

OSS generates and manages data encryption keys and uses high-strength, multi-factor security measures for protection. Data is encrypted using the industry-standard 256-bit Advanced Encryption Standard (AES-256).

Configuration methods:

  • Configure the bucket encryption method

    Set the bucket encryption method to OSS-managed and specify the encryption algorithm as AES256. Then, all objects uploaded to this bucket are encrypted by default.

  • Configure the target object's encryption method

    To enable server-side encryption using an OSS-managed key, include the x-oss-server-side-encryption parameter in your request when you upload an object or modify its metadata. Set the value of this parameter to AES256. For more information, see PutObject.

Related API operations

The preceding operations are based on API calls. If your application has high customization requirements, you can directly call REST API operations. To call a REST API operation, you must manually write code to calculate the signature. For more information, see PutBucketEncryption.

FAQ

After I configure an encryption method for a bucket, does OSS encrypt the existing objects?

OSS encrypts only the objects that are uploaded after the server-side encryption configuration takes effect. It does not encrypt existing objects. To encrypt existing objects, you can use the CopyObject operation to overwrite them.