server-side encryption, server-side encryption, server-side encryption

更新时间:
复制 MD 格式

When you upload an object to a bucket for which server-side encryption is enabled, OSS encrypts the object and stores the encrypted object. When you download an object through a GetObject request, OSS automatically decrypts the encrypted object and returns it to the user. In addition, OSS returns a x-oss-server-side-encryption in the response header to indicate that the object is encrypted on the server.

Note

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

Scenarios

OSS protects data at rest by using server-side encryption. It is suitable for scenarios where high security or compliance requirements are required for file storage. For example, the storage of deep learning sample files and the storage of online collaboration document data.

Precautions

  • 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, Australia (Sydney), Malaysia (Kuala Lumpur), Indonesia (Jakarta), Philippines (Manila), Thailand (Bangkok), India (Mumbai), Germany (Frankfurt), UK (London), UAE (Dubai) the region supports server-side encryption.

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

  • 无地域属性存储空间仅支持SSE-OSS加密方式,不支持SSE-KMS加密方式。

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

  • Configuring or changing the server-side encryption method of a bucket does not affect the server-side encryption method 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

Use scenarios

Remark

Billing rule

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 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 an 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 keys.

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

None

Free of charge.

Configure static website hosting

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.

    Parameter

    description

    Encryption Method

    Select the encryption method to encrypt objects in the bucket. You can use the default CMK or specify a CMK:

    • 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 by using a different key. OSS also uses master keys to encrypt the keys.

    • KMS: The default CMK managed by KMS or a specific 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

    可选择AES256SM4加密算法。Only the AES256 encryption algorithm is supported.

    Encryption Key

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

    The key used to encrypt the disk. 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. You can use the default CMK or specify a CMK:

    • alias/acs/oss(CMK ID): The default CMK managed by KMS is used to generate keys for 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 in which the bucket is located 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 the encryption method to encrypt objects in the bucket. You can use the default CMK or specify a CMK:

    • 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 by using a different key. OSS also uses master keys to encrypt the keys.

    • KMS: The default CMK managed by KMS or a specific 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

    可选择AES256SM4加密算法。Only the AES256 encryption algorithm is supported.

    Encryption Key

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

    The key used to encrypt the disk. 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. You can use the default CMK or specify a CMK:

    • alias/acs/oss(CMK ID): The default CMK managed by KMS is used to generate keys for 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 in which the bucket is located 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 only 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.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
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 this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. 
$provider = new EnvironmentVariableCredentialsProvider();
// The endpoint is set to China (Hangzhou) in this example. Specify the actual endpoint for other regions.
$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({
  // Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
  region: 'yourregion',
  // 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,
  authorizationV4: true,
  // Set bucket to the name of your bucket.
  bucket: 'yourbucketname'
});

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

    const result = await client.putBucketEncryption("bucket-name", {
      SSEAlgorithm: "AES256", // This example shows how to set AES256 encryption. If you use KMS encryption, you must add the KMSMasterKeyID property.
      // KMSMasterKeyID: "yourKMSMasterKeyId". Set the KMS key ID. You can set this parameter if the encryption method is KMS. If the value of SSEAlgorithm is KMS and you use a specified key for encryption, you must enter the key ID. Otherwise, this parameter must be 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.ProviderAuthV4(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 ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of the bucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

# 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";
// 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 the OSS account information. */
            
    /* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Set the bucket name. Example: examplebucket. */
    std::string BucketName = "examplebucket";

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

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    SetBucketEncryptionRequest setrequest(BucketName);
    setrequest.setSSEAlgorithm(SSEAlgorithm::KMS);
    /* Set server-side encryption using 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 network and other 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 running this code example, make sure that the environment variable OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET are set. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. 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";
        // Enter 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 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 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 object. 
            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 the access credential from the environment variable. Before running this code example, make sure that the environment variable OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET are set. 
$provider = new EnvironmentVariableCredentialsProvider();
// Set yourEndpoint to the endpoint of the region where the bucket is located. For example, in the China (Hangzhou) region, set the Endpoint parameter 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. The full path of the object cannot contain the bucket name. 
$object = "exampledir/exampleobject.txt";
// Enter 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 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 AES256. 
        "x-oss-server-side-encryption"=>"AES256",
    );
    // Call the uploadFile method to upload an object and pass in 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, in the China (Hangzhou) region, set Region to oss-cn-hangzhou. 
  region: "oss-cn-hangzhou",
  // Obtain the access credential from the environment variable. 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 bucket name. 
  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. The full path of the object cannot contain the bucket name. 
      "exampledir/exampleobject.txt",
      // Enter 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 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 the access credential from the environment variable. Before running this code example, make sure that the environment variable OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET are set. 
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())

# Set yourEndpoint to the endpoint of the region where the bucket is located. For example, in the China (Hangzhou) region, set the Endpoint parameter 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 path of the local file, the file is uploaded from the local 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 AES256. 
    headers = {
        'x-oss-server-side-encryption': 'AES256',
    }

    # Specify the full path of the object. The full path of the object 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 the access credential from the environment variable. Before running this code example, make sure that the environment variable OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET 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, in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify other regions based on your business needs. 
	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. 
  // Enter 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 of 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 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 a created 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 an encryption method for the object.

Use the OSS API

If your business requires a high level of customization, you can directly call RESTful API operations. To directly call an API, you need to 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 a created bucket, see PutBucketEncryption.

  • The REST API allows you to specify the server-side encryption method for files when you upload them. For more information, see PutObject.

Use KMS-managed keys for encryption and decryption

You can use CMKs managed by KMS to generate encryption keys to encrypt data. You can use the envelope encryption mechanism to further prevent unauthorized data access. With KMS, you can focus on business functions such as data encryption and decryption and electronic signature verification. You do not need to spend a lot of costs to ensure the confidentiality, integrity, and availability of keys.

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

image

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

  • The default KMS-managed CMK

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

    Configuration methods:

    • Configure the server-side encryption method of a bucket

      Set the bucket encryption method to KMS,指定加密算法为AES256SM4, but do not specify a CMK ID. This way, objects uploaded to this bucket are encrypted.

    • Configure the encryption method of 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. 如需修改加密算法为SM4,您还需增加x-oss-server-side-data-encryption参数,并设置参数值为SM4For 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 the server-side encryption method of a bucket

      Set the bucket encryption method to KMS,指定加密算法为AES256SM4, and specify the CMK ID. This way, objects uploaded to this bucket are encrypted.

    • Configure the encryption method of 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. 如需修改加密算法,您还需增加x-oss-server-side-data-encryption参数,并设置参数值为SM4For 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. OSS server-side encryption uses AES-256 to encrypt your data. AES-256 is one of the advanced encryption standard algorithms.和国密SM4The algorithm.

The configuration method is as follows:

  • Configure the bucket encryption method

    Set the bucket encryption method to fully managed by OSS and set the encryption algorithm to AES256SM4. By default, all objects uploaded to the bucket are encrypted.

  • Configure the encryption mode for the destination 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 value to AES256SM4. In this case, OSS uses the key that is fully managed by OSS to encrypt the object. For more information, see PutObject.

Permission description

The following table describes the permissions of a RAM user to use server-side encryption and decryption in different scenarios.

Note

For more information about how to grant permissions to a RAM user, see Grant a custom policy to a RAM user.

  • Configure an encryption method for a bucket

    • You have the management permissions on the destination bucket.

    • Has PutBucketEncryption and GetBucketEncryption permissions.

    • If you set Encryption Method to SSE-KMS and specify a CMK ID, you must have the ListKeys, Listalias, ListAliasesByKeyId, and DescribeKey permissions. The RAM policy authorization policy in this scenario is as follows:

      {
        "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 allow the RAM user to use only a specific CMK, enter the CMK ID. 
            ]
          }
        ]
      }
  • Upload an object to a bucket for which the server-side 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 server-side encryption method to SSE-KMS for a bucket and use a specific 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 to the RAM user:

      {
        "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 allow the RAM user to use only a specific CMK, enter the CMK ID. 
            ]
          }
        ]
      }
  • Download an object from a bucket for which the server-side encryption method is configured

    • The permissions to access objects in the bucket.

    • The permissions to call the Decrypt operation if you want to set the server-side encryption method to SSE-KMS for a bucket and use a specific CMK. The following sample code provides an example on how to grant a RAM user the preceding permissions by attaching a RAM policy to the RAM user:

      {
        "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 allow the RAM user to use only a specific CMK 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.