Object Storage Service (OSS) supports server-side encryption. When you upload an object to a bucket for which server-side encryption is enabled, OSS encrypts and then stores the object. When you download an encrypted object, OSS decrypts and then returns the decrypted object. A header is added to the response to indicate that the object is encrypted on the OSS server.

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 automatically encrypt data retrieved by using mirroring-based back-to-origin.
  • Only one 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 the encryption method for a single object when you upload or copy the object. In this case, the encryption method configured for the object takes precedence. For more information, see PutObject.

Encryption methods

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

Encryption method Description Scenario Precautions Billing
Server-side encryption that uses KMS-managed CMKs (SSE-KMS) You can use the default customer master key (CMK) managed by Key Management Service (KMS) or specify a CMK to encrypt or decrypt data. 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 can specify a 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.
  • SSE-KMS encrypts only the data in the object. The metadata of the object is not encrypted.
KMS charges you when you call API operations to encrypt or decrypt data by using SSE-KMS. For more information about the fees, see Billing.
Server-side encryption that uses OSS-managed keys (SSE-OSS) You can use SSE-OSS to encrypt each object. To improve security, OSS uses master keys that are rotated on a regular basis to encrypt data keys. Only basic encryption capabilities are required. You 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, go to the KMS product page to 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, go to the KMS product page to 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({
  region: "<yourRegion>",
  // 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>",
  bucket: "<yourBucketName>"
});

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

    let result = await store.putBucketEncryption("bucket-name", {
      SSEAlgorithm: "AES256", // The AES-256 encryption method is configured here as an example. To use KMS for encryption, you must configure KMSMasterKeyID.
      // KMSMasterKeyID: "<yourKMSMasterKeyId>". Configure the CMK ID when SSEAlgorithm is set to KMS and a specified CMK is used for encryption. In other cases, this element must be set to null.
    });
    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 Object Storage Service (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>')
# In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')

# 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 when 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;
var endpoint = "<yourEndpoint>";
// 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 your RAM user, log on to the RAM console.
var accessKeyId = "<yourAccessKeyId>";
var accessKeySecret = "<yourAccessKeySecret>";
var bucketName = "<yourBucketName>";
// 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. 
  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 OSS account information.*/
    std::string AccessKeyId = "yourAccessKeyId";
    std::string AccessKeySecret = "yourAccessKeySecret";
    std::string Endpoint = "yourEndpoint";
    std::string BucketName = "yourBucketName";

    /*Initialize network resources.*/
    InitializeSdk();

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

    SetBucketEncryptionRequest setrequest(BucketName);
    setrequest.setSSEAlgorithm(SSEAlgorithm::KMS);
undefined   /*Configure KMS-based server-side encryption for a bucket.*/
    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 network resources.*/
    ShutdownSdk();
    return 0;
}

Use ossutil

Method 1: Enable 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 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 only need to focus on the data encryption, data decryption, and digital signature generation and verification features of your business.

The following figure shows the logic of server-side encryption based on SSE-KMS. Encryption 1
When you use SSE-KMS to encrypt data, you can use the following keys:
  • Use the default CMK managed by KMS

    For this method, OSS uses different keys that are generated by the default KMS-managed CMK to encrypt different objects, 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. Objects uploaded to the 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 value of the parameter to KMS. In this case, OSS uses the default CMK that is managed by KMS and uses the AES-256 encryption algorithm to encrypt the object. For more information, see PutObject.

  • Use Bring Your Own Key (BYOK)

    After you use the BYOK material in the KMS console to generate a CMK, the keys generated by a specified CMK that is managed by KMS are used to encrypt different objects and the specified CMK ID is recorded in the metadata of the encrypted object. Objects are decrypted only when they are downloaded by users who have the permissions to decrypt the objects.

    You can obtain your BYOK material from one of the following sources:
    • BYOK material provided by Alibaba Cloud: When you create a key on KMS, you can select Alibaba Cloud KMS as the source of the key material.
    • BYOK material provided by the user: When you create a key on KMS, you can select External as the source of the key material and import the 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. 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 value of the parameter to KMS. In addition, include the x-oss-server-side-encryption-key-id parameter in the request and set the value of the parameter to a specified CMK ID. In this case, OSS uses the specified CMK that is 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 the keys used to encrypt data, and provides strong and multi-factor security measures to protect data. SSE-OSS uses AES-256, which is one of the advanced encryption standard algorithms to encrypt your data.

Configuration methods:

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

    Set the default encryption method to SSE-OSS and specify AES-256 as the encryption algorithm. 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 value of the parameter to AES256. In this case, the object is encrypted by using an OSS-managed key. For more information, see PutObject.

Permissions

If a RAM user wants to use server-side encryption to encrypt and decrypt objects in the following scenarios, the RAM user must have the following permissions.
  • 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. To grant a RAM user the preceding permissions, configure a RAM policy based on the following example in the RAM console:
      {
        "Version": "1",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": [
              "kms:List*",
              "kms:DescribeKey"    
            ],
            "Resource": [
              "acs:kms:*:141661496593****:*" // In this example, 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. To grant a RAM user the preceding permissions, configure a RAM policy based on the following example in the RAM console:
      {
        "Version": "1",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": [
              "kms:List*",
              "kms:DescribeKey",
              "kms:GenerateDataKey",
              "kms:Decrypt"
            ],
            "Resource": [
              "acs:kms:*:141661496593****:*" // In this example, 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. To grant a RAM user the preceding permissions, configure a RAM policy based on the following example in the RAM console:
      {
        "Version": "1",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": [
          "kms:Decrypt"
            ],
            "Resource": [
              "acs:kms:*:141661496593****:*" // In this example, 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, enter the CMK ID. 
            ]
          }
        ]
      }

FAQ

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

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