Object Storage Service (OSS) encrypts objects uploaded to a bucket that has server-side encryption enabled and stores the encrypted objects. When you call GetObject to download an object, the object is retrieved after OSS decrypts the object. The x-oss-server-side-encryption header is contained in the response to declare that the object is encrypted on the server side.

Note For more information about the response header, see Response headers.

Scenarios

OSS uses server-side encryption to protect static data. You can use this method in scenarios in which additional security or compliance is required, such as the storage of deep learning samples and online collaborative documents.

Usage notes

  • Server-side encryption cannot be enabled in the China (Nanjing - Local Region) region.
  • Server-side encryption cannot automatically encrypt data retrieved by using mirroring-based back-to-origin.
  • Only a single server-side encryption method can be used for an object at a time.
  • If you configure server-side encryption for a bucket, you can still configure encryption for a single object when you upload or copy it. In this case, the encryption method configured for the object takes precedence. For more information, see PutObject.

Encryption method

The following table describes the server-side encryption methods that you can use in different scenarios.

Encryption method Description Scenario Notes Billing
Server-side encryption that uses KMS-managed CMKs (SSE-KMS) The encryption and decryption by using the default customer master key (CMK) of Key Management Service (KMS) or a specified CMK. This method is cost-effective because you do not need to send user data to the KMS server over networks for encryption or decryption. You must use a customer-managed CMK to meet security and compliance requirements.
  • The key used to encrypt the object is also encrypted and written into the metadata of the object.
  • Only data in the object is encrypted. The metadata of the object is not encrypted.
KMS charges you when you call API operations to encrypt or decrypt data by using CMKs stored in KMS. For more information about the fees, see Billing of KMS.
Server-side encryption that uses OSS-managed keys (SSE-OSS) The encryption by using an OSS-managed key for each object. To improve security, OSS uses master keys that are rotated on a regular basis to encrypt data keys. You want only basic encryption capabilities and do not need to manage keys on your own. None Free of charge

Use the OSS console

Method 1: Enable server-side encryption when you create a bucket

  1. Log on to the OSS console.
  2. In the left-side navigation pane, click Buckets. On the Buckets page, click Create Bucket.
  3. In the Create Bucket panel, configure the parameters.
    Configure the following parameters in the Server-side Encryption section:
    • Encryption Method: Select an encryption method for the bucket.
      • None: Server-side encryption is disabled.
      • OSS-Managed: Keys managed by OSS are used to encrypt objects in the bucket. OSS uses data keys to encrypt objects. In addition, OSS uses regularly rotated master keys to encrypt data keys.
      • KMS: The default customer master key (CMK) stored in Key Management Service (KMS) or the specified CMK is used to encrypt and decrypt data.

        Before you use SSE-KMS, you must activate KMS. For more information, see Activate KMS.

    • Encryption Algorithm: Only 256-bit Advanced Encryption Standard (AES-256) is supported.
    • CMK: You can set this parameter if Encryption Method is set to KMS. You can configure the following parameters for a CMK:
      • alias/acs/oss: The default CMK stored in KMS is used to encrypt different objects and decrypt the objects when the objects are downloaded.
      • CMK ID: The keys generated by a specified CMK are used to encrypt different objects and the specified CMK ID is recorded in the metadata of the encrypted object. Objects are decrypted when they are downloaded by users who are granted decryption permissions. Before you specify a CMK ID, you must create a normal key or an external key in the same region as the bucket in the KMS console. For more information, see Import key material.

    For information about other parameters, see Create buckets.

  4. Click OK.

Method 2: 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, click the name of the desired bucket.
  3. Choose Basic Settings > Server-side Encryption.
  4. In the Server-side Encryption section, click Configure.
    Configure the following parameters in the Server-side Encryption section:
    • Encryption Method: Select an encryption method for the bucket.
      • None: Server-side encryption is disabled.
      • OSS-Managed: Keys managed by OSS are used to encrypt objects in the bucket. OSS uses data keys to encrypt objects. In addition, OSS uses regularly rotated master keys to encrypt data keys.
      • KMS: The default customer master key (CMK) stored in Key Management Service (KMS) or the specified CMK is used to encrypt and decrypt data.

        Before you use SSE-KMS, you must activate KMS. For more information, see Activate KMS.

    • Encryption Algorithm: Only 256-bit Advanced Encryption Standard (AES-256) is supported.
    • CMK: You can set this parameter if Encryption Method is set to KMS. You can configure the following parameters for a CMK:
      • alias/acs/oss: The default CMK stored in KMS is used to encrypt different objects and decrypt the objects when the objects are downloaded.
      • CMK ID: The keys generated by a specified CMK are used to encrypt different objects and the specified CMK ID is recorded in the metadata of the encrypted object. Objects are decrypted when they are downloaded by users who are granted decryption permissions. Before you specify a CMK ID, you must create a normal key or an external key in the same region as the bucket in the KMS console. For more information, see Import key material.
  5. Click save.
    Notice The configurations of the default encryption method for a bucket do not affect the encryption configurations of existing objects within the bucket.

Use OSS SDKs

The following code provides examples on how to configure server-side encryption for a bucket by using OSS SDKs for common programming languages. For more information about how to configure server-side encryption for a bucket by using OSS SDKs for other programming languages, see Overview.

import com.aliyun.oss.*;
import com.aliyun.oss.model.*;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify the actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to access OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the CMK ID managed by KMS. Example: e1935511-cf88-1123-a0f8-1be8d2511***. 
        String kmsId = "e1935511-cf88-1123-a0f8-1be8d2511***";

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // Configure server-side encryption for the bucket. 
            ServerSideEncryptionByDefault applyServerSideEncryptionByDefault = new ServerSideEncryptionByDefault(SSEAlgorithm.KMS);
            applyServerSideEncryptionByDefault.setKMSMasterKeyID(kmsId);
            ServerSideEncryptionConfiguration sseConfig = new ServerSideEncryptionConfiguration();
            sseConfig.setApplyServerSideEncryptionByDefault(applyServerSideEncryptionByDefault);
            SetBucketEncryptionRequest request = new SetBucketEncryptionRequest(bucketName, sseConfig);
        } 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
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\OssClient;
use OSS\Core\OssException;
use OSS\Model\ServerSideEncryptionConfig;

// Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console.
$accessKeyId = "<yourAccessKeyId>";
$accessKeySecret = "<yourAccessKeySecret>";
// The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";

$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false);

try {
    // Set the default server-side encryption method of the bucket to SSE-OSS.
    $config = new ServerSideEncryptionConfig("AES256");
    $ossClient->putBucketEncryption($bucket, $config);

    // Set the default server-side encryption method of the bucket to KMS without specifying a CMK ID.
    $config = new ServerSideEncryptionConfig("KMS");
    $ossClient->putBucketEncryption($bucket, $config);

    // Set the default server-side encryption method of the bucket to KMS and specify a CMK ID.
    $config = new ServerSideEncryptionConfig("KMS", "your kms id");
    $ossClient->putBucketEncryption($bucket, $config);
} catch (OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}

print(__FUNCTION__ . ": OK" . "\n"); 
const OSS = require("ali-oss");

const store = 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',
  // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a Resource Access Management (RAM) user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
  accessKeyId: 'yourAccessKeyId',
  accessKeySecret: 'yourAccessKeySecret',
  // Specify yourbucketname as the name of the bucket. 
  bucket: 'yourbucketname'
});

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

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

putBucketEncryption();
# -*- coding: utf-8 -*-
import oss2
from oss2.models import ServerSideEncryptionRule
# The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# 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 the bucket name. Example: examplebucket. 
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')

# Create encryption configurations for the bucket. In this example, AES-256 encryption is used. 
rule = ServerSideEncryptionRule()
rule.sse_algorithm = oss2.SERVER_SIDE_ENCRYPTION_AES256
# Specify the customer master key (CMK) ID. The CMK ID can be specified only if you use the OSS-KMS encryption method. If you want to use a specified CMK for encryption, enter the CMK ID. If you want to use the default CMK managed by Key Management Service (KMS) for encryption, leave this parameter empty. If you use AES-256 encryption, you must leave this parameter empty. 
rule.kms_master_keyid = ""

# Apply the encryption configurations to the bucket. 
result = bucket.put_bucket_encryption(rule)

# Display the returned HTTP status code. 
print('http response code:', result.status)
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";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
var accessKeyId = "yourAccessKeyId";
var accessKeySecret = "yourAccessKeySecret";
// Specify the bucket name. Example: examplebucket. 
var bucketName = "examplebucket";
// Create an OSSClient instance. 
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
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 (
  "fmt"
  "os"

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

func main() {
  // 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. 
  // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
  client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret")
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }

  // Initialize an encryption rule. In this example, AES-256 encryption is used. 
  config := oss.ServerEncryptionRule{SSEDefault: oss.SSEDefaultRule{SSEAlgorithm: "AES256"}}
  err = client.SetBucketEncryption("yourBucketName", config)
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the information about the account that is used to access OSS. */
    /* The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. */
    std::string AccessKeyId = "yourAccessKeyId";
    std::string AccessKeySecret = "yourAccessKeySecret";
    /* 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. */
    std::string Endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize resources such as networks. */
    InitializeSdk();

    ClientConfiguration conf;
    OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);

    SetBucketEncryptionRequest setrequest(BucketName);
    setrequest.setSSEAlgorithm(SSEAlgorithm::KMS);
undefined   /* Set the default encryption method for the bucket to SSE-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;
        ShutdownSdk();
        return -1;
    }

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

Use ossutil

Method 1: Configure server-side encryption when you create a bucket

For more information about how to enable server-side encryption when you create a bucket by using ossutil, see bucket-encryption.

Method 2: Specify an encryption method for an object when you upload the object

For more information about how to specify an encryption method for an object when you upload the object, see Specify an encryption method for an object when you upload the object.

Use RESTful APIs

If your program requires more custom options to configure retention policies, you can call RESTful API operations. In this case, you must write code to calculate the signature. For more information, see PutBucketEncryption.

Use KMS-managed CMKs for encryption and decryption

You can use a CMK managed by KMS to generate data keys for object encryption. KMS eliminates the need to manually maintain the security, integrity, and availability of your keys. You need to only focus on the data encryption, data decryption, and digital signature generation and verification features of your business.

The following figure shows the encryption logic of SSE-KMS. Encryption method 1
When you use SSE-KMS to encrypt data, you can use the following keys:
  • CMKs stored in KMS

    For this method, OSS generates different keys to encrypt different objects by using the default CMK stored in KMS, and automatically decrypts an object when the object is downloaded. The first time you use SSE-KMS, OSS creates a CMK in KMS.

    Configuration methods:

    • Configure the default server-side encryption method for a bucket

      Set the default server-side encryption method for a bucket to KMS, but do not specify a CMK ID. This way, objects uploaded to this bucket are encrypted.

    • Configure an encryption method for a specified object

      When you upload an object or modify the metadata of an object, include the x-oss-server-side-encryption parameter in the request and set the parameter to KMS. This way, OSS uses the default CMK managed by KMS and uses the AES-256 encryption algorithm to encrypt the object. For more information, see PutObject.

  • CMKs generated by using Bring Your Own Key (BYOK)

    You can use the BYOK material to generate a CMK in the KMS console. OSS can use the CMK to generate different data keys to encrypt different objects. The CMK ID is recorded in the metadata of the encrypted objects. The objects are decrypted only when they are downloaded by users who have permissions to decrypt the objects.

    You may obtain your BYOK material from one of the following sources:
    • BYOK material provided by Alibaba Cloud: When you create a CMK in the KMS console, you can select Alibaba Cloud KMS as the source of the key material.
    • BYOK material managed by the user: When you create a CMK in the KMS console, you can select external to import external key material. For more information about how to import the key material, see Import key material.
    Configuration methods:
    • Configure the default server-side encryption method for a bucket

      Set the default server-side encryption method for a bucket to KMS, and specify the CMK ID. This way, objects uploaded to this bucket are encrypted.

    • Configure an encryption method for a specified object

      When you upload an object or modify the metadata of an object, include the x-oss-server-side-encryption parameter in the request and set the parameter to KMS. In addition, include the x-oss-server-side-encryption-key-id parameter in the request and set the parameter to the specified CMK ID. This way, OSS uses the specified CMK managed by KMS and the AES-256 encryption algorithm to encrypt the object. For more information, see PutObject.

Use OSS-managed keys for encryption and decryption

OSS generates and manages data keys used to encrypt data, and provides strong and multi-factor security measures to protect data. OSS server-side encryption uses AES-256 to encrypt your data. AES-256 is one of the advanced encryption standard algorithms.

Configuration methods:

  • Configure the default server-side encryption method for a bucket

    Set the default encryption method to SSE-OSS and specify the encryption algorithm as AES-256. This way, all objects uploaded to the bucket are encrypted by default.

  • Configure an encryption method for a specified object

    When you upload an object or modify the metadata of an object, include the x-oss-server-side-encryption parameter in the request and set the parameter to AES256. This way, OSS uses OSS-managed keys to encrypt the object. For more information, see PutObject.

Required permissions

If a RAM user wants to use server-side encryption to encrypt and decrypt objects in different scenarios, the RAM user must have the required permissions.

Note For more information about how to grant permissions to a RAM user, see Attach a custom policy to a RAM user.
  • Configure the default encryption method for a bucket
    • The permissions to manage the bucket.
    • The permissions to call the PutBucketEncryption and GetBucketEncryption operations.
    • The permissions to call the ListKeys, Listalias, ListAliasesByKeyId, and DescribeKeys operations when you set the encryption method to SSE-KMS and use a specified CMK ID to encrypt data. The following code provides an example on how to grant a RAM user the preceding permissions by using a RAM policy:
      {
        "Version": "1",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": [
              "kms:List*",
              "kms:DescribeKey"    
            ],
            "Resource": [
              "acs:kms:*:141661496593****:*" // The RAM user is allowed to use all CMKs that belong to the Alibaba Cloud account. To specify that only a specific CMK is available for the RAM user, enter the CMK ID. 
            ]
          }
        ]
      }
  • Upload an object to a bucket for which the default encryption method is configured
    • The permissions to upload objects to the bucket.
    • The permissions to call the ListKeys, Listalias, ListAliasesByKeyId, DescribeKeys, GenerateDataKey, and kms:Decrypt operations when you set the encryption method to KMS and use a specified CMK ID to encrypt data. The following code provides an example on how to grant a RAM user the preceding permissions by using a RAM policy:
      {
        "Version": "1",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": [
              "kms:List*",
              "kms:DescribeKey",
              "kms:GenerateDataKey",
              "kms:Decrypt"
            ],
            "Resource": [
              "acs:kms:*:141661496593****:*" // The RAM user is allowed to use all CMKs that belong to the Alibaba Cloud account. To specify that only a specific CMK is available for the RAM user, enter the CMK ID. 
            ]
          }
        ]
      }
  • Download an object from a bucket for which the default encryption method is configured
    • The permissions to access objects in the bucket.
    • The permissions to call the Decrypt operation when you set the encryption method to KMS and use a specified CMK ID to encrypt data. The following code provides an example on how to grant a RAM user the preceding permissions by using a RAM policy:
      {
        "Version": "1",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": [
          "kms:Decrypt"
            ],
            "Resource": [
              "acs:kms:*:141661496593****:*" // The RAM user has the permissions to use all CMKs that belong to the Alibaba Cloud account. To specify that only a specific CMK is available for the RAM user to decrypt objects, enter the CMK ID. 
            ]
          }
        ]
      }

FAQ

Q: Does OSS encrypt existing objects in a bucket after I configure server-side encryption for the bucket?

A: No, OSS encrypts only objects that are uploaded after server-side encryption is configured for the bucket. If you want to encrypt existing objects in the bucket, you can call the CopyObject operation to overwrite the existing objects.