All Products
Search
Document Center

Object Storage Service:Server-side encryption

Last Updated:Nov 14, 2024

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

Note

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

Scenarios

OSS uses server-side encryption to protect static data. You can configure this feature 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 is supported in the following regions: China (Hangzhou), China (Shanghai), China (Qingdao), China (Beijing), China (Zhangjiakou), China (Hohhot), China (Ulanqab), China (Shenzhen), China (Heyuan), China (Guangzhou), China (Chengdu), China (Hong Kong), US (Silicon Valley), US (Virginia), Japan (Tokyo), South Korea (Seoul), Singapore, Malaysia (Kuala Lumpur), Indonesia (Jakarta), Philippines (Manila), Thailand (Bangkok), Germany (Frankfurt), UK (London), and UAE (Dubai).

  • If you want to perform object upload, download, or access operations on a bucket for which server-side encryption that uses KMS-managed CMKs (SSE-KMS) is configured, make sure that you have the permissions to use the specified customer master key (CMK) and the request is not anonymous. Otherwise, the request fails and the This request is forbidden by kms error message is returned.

  • By default, OSS does not encrypt objects that are obtained by using mirroring-based back-to-origin.

  • Configuring or changing the server-side encryption method of a bucket does not affect the encryption methods of existing objects in the bucket.

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

  • If you have configured server-side encryption for a bucket, you can still use a different encryption method for objects when you upload or copy them to the bucket. The encryption method configured for the objects 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

Remarks

Billing rule

SSE-KMS

You can use the default 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 data to the KMS server over networks for encryption or decryption.

You must 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.

  • Only data in the object is encrypted. The metadata of the object is not encrypted.

You are charged 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)

You can use a key managed by OSS to encrypt an object. To improve security, OSS uses master keys to encrypt cryptographic keys.

Only basic encryption capabilities are required. You do not need to manually manage keys.

None.

Free of charge.

Procedure

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. In the left-side navigation pane, click Buckets. On the Buckets page, click Create Bucket.

  3. In the Create Bucket panel, configure the parameters.

    The following table describes the parameters that you can configure for server-side encryption.

    Parameter

    Description

    Encryption Method

    Select an encryption method to encrypt objects in the bucket. Valid values:

    • None: Server-side encryption is disabled.

    • OSS-Managed: The keys managed by OSS are used to encrypt objects in the bucket. OSS encrypts each object with a different key. OSS also uses master keys to encrypt cryptographic keys.

    • KMS: The default CMK managed by KMS or the specified CMK is used to encrypt and decrypt objects.

      To use KMS-managed CMKs, you must activate KMS. For more information, see Purchase a dedicated KMS instance.

    Encryption Algorithm

    Only AES-256 is supported.

    CMK

    Select a CMK. This parameter is available only when KMS is selected for Encryption Method.

    A CMK is in the <alias>(CMK ID) format. <alias> is the alias of the CMK and CMK ID is the ID of the CMK. Valid values:

    • alias/acs/oss(CMK ID): The default CMK managed by KMS is used to generate keys for target encryption and decryption.

    • alias/<cmkname>(CMK ID): A custom CMK is used to generate keys for object encryption. The CMK ID is recorded in the metadata of the encrypted objects. Objects are decrypted when they are downloaded by users who have the decryption permissions. <cmkname> is the optional name of the CMK that you configured when you created the CMK.

      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 Create a CMK.

    For more information about how to configure other parameters, see Create a bucket.

  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 left-side navigation tree, choose Content Security > Server-side Encryption.

  4. On the Server-side Encryption page, click Settings and configure the parameters. The following table describes the parameters.

    Parameter

    Description

    Encryption Method

    Select an encryption method to encrypt objects in the bucket. Valid values:

    • None: Server-side encryption is disabled.

    • OSS-Managed: The keys managed by OSS are used to encrypt objects in the bucket. OSS encrypts each object with a different key. OSS also uses master keys to encrypt cryptographic keys.

    • KMS: The default CMK managed by KMS or the specified CMK is used to encrypt and decrypt objects.

      To use KMS-managed CMKs, you must activate KMS. For more information, see Purchase a dedicated KMS instance.

    Encryption Algorithm

    Only AES-256 is supported.

    CMK

    Select a CMK. This parameter is available only when KMS is selected for Encryption Method.

    A CMK is in the <alias>(CMK ID) format. <alias> is the alias of the CMK and CMK ID is the ID of the CMK. Valid values:

    • alias/acs/oss(CMK ID): The default CMK managed by KMS is used to generate keys for target encryption and decryption.

    • alias/<cmkname>(CMK ID): A custom CMK is used to generate keys for object encryption. The CMK ID is recorded in the metadata of the encrypted objects. Objects are decrypted when they are downloaded by users who have the decryption permissions. <cmkname> is the optional name of the CMK that you configured when you created the CMK.

      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 Create a CMK.

  5. Click Save.

Method 2: Enable server-side encryption for a bucket when you upload an object to the bucket

For more information, see Simple upload.

Use OSS SDKs

Method 1: Enable server-side encryption for a bucket

You can use OSS SDKs to enable server-side encryption for an existing bucket. You cannot use OSS SDKs to enable server-side encryption when you create a bucket. The following sample code provides examples on how to enable server-side encryption for an existing bucket by using OSS SDKs for common programming languages. For more information about how to enable server-side encryption for an existing bucket by using OSS SDKs for other programming languages, see Overview.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
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. 
        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
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;
use OSS\Model\ServerSideEncryptionConfig;

// 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 = new EnvironmentVariableCredentialsProvider();
// In this example, the China (Hangzhou) region is used as the endpoint. Specify your actual endpoint. 
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";

$config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);

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 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();
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import ServerSideEncryptionRule
# Obtain access credentials from the 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. 
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# 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 name of the bucket. 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 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 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";
// 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";
// 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 (
	"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. 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 network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    /* 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);

    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: Enable server-side encryption for a bucket when you upload an object to the bucket

The following sample code provides examples on how to enable server-side encryption for a bucket by using OSS SDKs for common programming languages when you upload an object to the object. For more information about how to enable server-side encryption for a bucket by using OSS SDKs for other programming languages when you upload an object to the bucket, see Overview.

Java

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
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 {
        // 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 full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
        String objectName = "exampledir/exampleobject.txt";
        // Specify the full path of the local file that you want to upload. Example: D:\\localpath\\examplefile.txt. 
        // By default, if you do not specify the full path of the local file, the local file is uploaded from the path of the project to which the sample program belongs. 
        String filePath= "D:\\localpath\\examplefile.txt";
        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        try {
            // Create an ObjectMetadata object and set the server-side encryption method to AES-256. 
            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 local 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 the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
$provider = new EnvironmentVariableCredentialsProvider();
// 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. 
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the name of the bucket. Example: examplebucket. 
$bucket= "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path of the object. 
$object = "exampledir/exampleobject.txt";
// Specify the full path of the local file that you want to upload. Example: D:\\localpath\\examplefile.txt. By default, if you do not specify the full path of the local file, the local file is uploaded from the path of 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 AES-256. 
        "x-oss-server-side-encryption"=>"AES256",
    );
    // Use the uploadFile method to upload the local 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({
  // 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: "oss-cn-hangzhou",
  // 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. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the name of the bucket. 
  bucket: "examplebucket",
});

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

async function put() {
  try {. 
    const result = await client.put(
      // Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path of the object. 
      "exampledir/exampleobject.txt",
      // Specify the full path of the local file that you want to upload. Example: D:\\localpath\\examplefile.txt. By default, if you do not specify the full path of the local file, the local file is uploaded from the path of 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 the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())

# 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. 
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'

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

# The file must be opened in binary mode. 
# Specify the full path of the local file. By default, if you do not specify the full path of the local file, the local file is uploaded from the path of the project to which the sample program belongs. 
local_file_path = 'D:\\examplefile.jpg'
with open(local_file_path, 'rb') as fileobj:
    # Use the seek method to read data from byte 1,000 of the file. The data is uploaded from byte 1000 to the last byte of the local file. 
    fileobj.seek(1000, os.SEEK_SET)
    # Use the tell method to obtain the current position. 
    current = fileobj.tell()

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

    # Specify the full path of the object. Do not include the bucket name in the full path of the object. 
    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 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 {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// 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. 
	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 name of the bucket. Example: examplebucket. 
	bucket, err := client.Bucket("examplebucket")
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
  // Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path of the object. 
  // Specify the full path of the local file that you want to upload. Example: D:\\localpath\\examplefile.txt. By default, if you do not specify the full path of the local file, the local file is uploaded from the path of the project to which the sample program belongs. 
  // Set the server-side encryption method to AES-256. 
	err = bucket.PutObjectFromFile("D:\\localpath\\examplefile.txt", "D:\\examplefile.jpg", oss.ServerSideEncryption("AES256"))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
}

Use ossutil

Method 1: Enable server-side encryption for a bucket

ossutil allows you to enable server-side encryption for an existing bucket. You cannot use ossutil to enable server-side encryption when you create a bucket.

For more information about how to enable server-side encryption for an existing bucket, see bucket-encryption.

Method 2: Enable server-side encryption for a bucket when you upload an object to the bucket

ossutil allows you to specify an encryption method for an object when you upload the object. For more information, see Upload an object and specify the encryption method of the object.

Use the OSS API

If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code.

  • The RESTful APIs allow you to enable server-side encryption for an existing bucket. You cannot enable server-side encryption when you create a bucket.

    For more information about how to enable server-side encryption for an existing bucket, see PutBucketEncryption.

  • The RESTful APIs allow you to specify the server-side encryption method for objects when you upload them. For more information, see PutObject.

Use KMS-managed CMKs for encryption and decryption

You can use a KMS-managed CMK to generate cryptographic keys for object encryption. The envelope encryption mechanism further prevents unauthorized data access. KMS eliminates the need to manually maintain the security, integrity, and availability of your keys. This way, you can focus on data encryption, data decryption, and digital signature generation and verification.

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

image

When you use SSE-KMS to encrypt data, you can use the following keys:

  • The default KMS-managed CMK

    OSS uses keys generated based on the default KMS-managed CMK to encrypt objects and decrypt objects when the objects are downloaded. The first time you use SSE-KMS, OSS creates a CMK in KMS.

    Configuration methods:

    • Configure server-side encryption for a bucket

      Set the encryption method of a bucket to KMS without specifying a CMK ID. This way, objects uploaded to this bucket are encrypted.

    • Configure an encryption method for a specific object

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

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

    After you use the BYOK material in the KMS console to generate a CMK, OSS uses keys generated based on the CMK to encrypt different objects and the CMK ID is recorded in the metadata of the encrypted objects. Objects are automatically decrypted only when they are downloaded by users that have the decryption permissions.

    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, select Alibaba Cloud KMS as the source of the key material.

    • BYOK material provided by the user: When you create a key on KMS, select External as the source of the key material and import the external key material. For more information about how to import an external key, see Import key material.

    Configuration methods:

    • Configure server-side encryption for a bucket

      Set the encryption method of a bucket to KMS and specify a CMK ID. This way, objects uploaded to this bucket are encrypted.

    • Configure an encryption method for a specific object

      When you upload an object or modify the metadata of the object, set the x-oss-server-side-encryption header to KMS in the request and specify the CMK ID by using the x-oss-server-side-encryption-key-id header. 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 multifactor security measures to protect data. SSE-OSS uses the AES-256 encryption algorithm to encrypt data.

Configuration methods:

  • Configure server-side encryption for a bucket

    Set the 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 specific 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. OSS uses the OSS-managed key 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 Common examples of RAM policies.

  • Configure server-side encryption for a bucket

    • The permissions to manage the bucket.

    • The permissions to call PutBucketEncryption and GetBucketEncryption.

    • The permissions to call the following operations if you want to set the encryption method to SSE-KMS and use a specified CMK to encrypt data: ListKeys, Listalias, ListAliasesByKeyId, and DescribeKey. The following sample code provides an example on how to grant a RAM user the preceding permissions by attaching 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 KMS-managed 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 an encryption method is configured

    • The permissions to upload objects to the bucket.

    • The permissions to call the following operations if you want to set the encryption method to SSE-KMS and use a specified CMK to encrypt data: ListKeys, ListAliases, ListAliasesByKeyId, DescribeKey, GenerateDataKey, and Decrypt. The following sample code provides an example on how to grant a RAM user the preceding permissions by attaching 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 an encryption method is configured

    • The permissions to access objects in the bucket.

    • The permissions to call the Decrypt operation if the encryption method is SSE-KMS and a specified CMK is used. The following sample code provides an example on how to grant a RAM user the preceding permissions by attaching 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

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.