When you upload an object to a bucket with server-side encryption enabled, Object Storage Service (OSS) encrypts the object before storing it. When you download the object using a GetObject request, OSS automatically decrypts the object and returns it to you. The x-oss-server-side-encryption header in the response indicates that the object was encrypted on the server side.
Note
For more information about the x-oss-server-side-encryption response header, see GetObject.
Scenarios
OSS provides data-at-rest protection through server-side encryption. This feature is suitable for applications that have high security or compliance requirements for data storage, such as storing deep learning sample files or online collaborative document data.
Encryption methods
OSS provides two server-side encryption methods for different scenarios. You can select a method based on your requirements.
Encryption method
Description
Scenarios
Notes
Billing
Encrypt and decrypt data using Key Management Service (KMS)-managed keys (SSE-KMS)
Use the default customer master key (CMK) managed by KMS or a specified CMK to encrypt and decrypt data. Data is encrypted and decrypted without being sent over the network to the KMS server.
This method is for scenarios where you need to use self-managed keys that you can specify for security and compliance purposes.
The key used to encrypt an object is also encrypted and stored in the object's metadata.
The SSE-KMS encryption method encrypts only object data, but not the object's metadata.
The KMS key created by default in the OSS console is free of charge.
If you use your own KMS key, fees are incurred in KMS. For more information, see KMS pricing.
Encrypt and decrypt data using OSS-managed keys (SSE-OSS)
Use a key that is fully managed by OSS to encrypt each object. For enhanced security, OSS also uses a master key to encrypt the data encryption key itself.
This method is for scenarios where you only need basic encryption and do not need to manage keys.
None.
Free of charge.
Notes
When you upload, download, or access objects in a bucket with SSE-KMS encryption enabled, ensure that you have permissions to use the specified CMK ID and that the request is not anonymous. Otherwise, the request fails and the This request is forbidden by kms error is returned.
Objects that are mirrored to a bucket using mirroring-based back-to-origin are not encrypted by default.
Enabling or modifying the encryption method for a bucket does not affect the encryption configuration of existing objects in the bucket.
Only one server-side encryption method can be used for an object at a time.
If you configure encryption for a bucket, you can still specify a different encryption method for an individual object when you upload or copy it. The encryption method specified for the object prevails. For more information, see PutObject.
Permissions
The following list describes the permissions that a Resource Access Management (RAM) user needs to use server-side encryption in different scenarios.
The PutBucketEncryption and GetBucketEncryption permissions.
If you set the encryption method to SSE-KMS and specify a CMK ID, the ListKeys, ListAliases, ListAliasesByKeyId, and DescribeKey permissions are also required. The following is a sample RAM policy for this scenario:
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"kms:List*",
"kms:DescribeKey"
],
"Resource": [
"acs:kms:*:141661496593****:*" // This policy lets you call all KMS keys under the Alibaba Cloud account ID. To allow the use of only a specific CMK, enter the corresponding CMK ID.
]
}
]
}
Upload an object to an encrypted bucket
Permissions to upload objects to the destination bucket.
If the encryption method is set to KMS and a CMK ID is specified, the ListKeys, ListAliases, ListAliasesByKeyId, DescribeKey, GenerateDataKey, and Decrypt permissions are also required. The following is a sample RAM policy for this scenario:
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"kms:List*",
"kms:DescribeKey",
"kms:GenerateDataKey",
"kms:Decrypt"
],
"Resource": [
"acs:kms:*:141661496593****:*"// This policy lets you call all KMS keys under the Alibaba Cloud account ID. To allow the use of only a specific CMK, enter the corresponding CMK ID.
]
}
]
}
Download an object from an encrypted bucket
Permissions to access objects in the destination bucket.
If the encryption method is set to KMS and a CMK ID is specified, the Decrypt permission is also required. The following is a sample RAM policy for this scenario:
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"kms:Decrypt"
],
"Resource": [
"acs:kms:*:141661496593****:*"// This policy grants permissions to decrypt data using all KMS keys under the Alibaba Cloud account ID. To grant permissions to decrypt data using a specific KMS key, enter the corresponding CMK ID.
]
}
]
}
Procedures
Important
If you purchase the key rotation value-added service for KMS, server-side encryption supports key rotation for KMS keys. After key rotation is enabled, the new key is used to encrypt only newly uploaded objects. The encryption keys of existing objects remain unchanged.
If you update the KMS encryption key in OSS, the new key is used to encrypt only newly uploaded objects. Objects uploaded before the key update are still encrypted with the old key. Therefore, do not delete the old key after the update. Otherwise, you cannot access existing objects.
Use the OSS console
Method 1: Enable server-side encryption for a bucket
Enable server-side encryption when you create a bucket
In the Create Bucket panel, configure the following parameters.
The following parameters are used to configure server-side encryption for a region:
Parameter
Description
Encryption Method
Select an encryption method for objects. Valid values:
None: Server-side encryption is disabled.
SSE-OSS: Use OSS-managed keys for encryption. OSS uses a different key to encrypt each object. For extra protection, OSS uses a master key to encrypt the data encryption key itself.
SSE-KMS: Use the default CMK managed by KMS or a specified CMK for encryption and decryption.
You need to configure this option only when you select KMS for server-side encryption.
Select an encryption key. The key is in the format of <alias>(CMK ID). <alias> is the alias of the CMK, and CMK ID is the ID of the CMK. Valid values:
alias/acs/oss(CMK ID): If you select this option, OSS uses the default service key to encrypt data in the bucket and automatically decrypts the data when you download objects from the bucket.
alias/<cmkname>(CMK ID): If you select this option, OSS uses the specified service key to encrypt data in the bucket and records the CMK ID in the metadata of the encrypted object. When a user with decryption permissions downloads the object, the object is automatically decrypted. <cmkname> is an optional alias for the CMK that you specified when you created the key.
Before you use a specified CMK ID, you must create a standard or external key in the same region as the bucket in the KMS console. For more information, see Create a CMK.
For more information about other parameters, see Create a bucket.
Click OK.
Enable server-side encryption for an existing bucket
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.
In the navigation pane on the left, choose Content Security > Server-side Encryption.
On the Server-side Encryption page, click Configure and configure the parameters.
Parameter
Description
Encryption Method
Select an encryption method for objects. Valid values:
None: Server-side encryption is disabled.
SSE-OSS: Use OSS-managed keys for encryption. OSS uses a different key to encrypt each object. For extra protection, OSS uses a master key to encrypt the data encryption key itself.
SSE-KMS: Use the default CMK managed by KMS or a specified CMK for encryption and decryption.
Only the AES256 encryption algorithm is supported.
CMK
This parameter is required only when you set Encryption Method to SSE-KMS.
Select an encryption key. The key is in the format of <alias>(CMK ID). <alias> is the alias of the CMK, and CMK ID is the ID of the CMK. Valid values:
Default Service Key: If you select this option, OSS generates a default service key to encrypt data in the bucket and automatically decrypts the data when you download objects from the bucket. The default service key created by OSS is in the format of alias/acs/oss (CMK ID). You can view this service key in the KMS console.
Note
Before you can view this service key in the KMS console, you must upload at least one object to the destination bucket to ensure that the corresponding encryption key is created and associated with your OSS service.
alias/<cmkname>(CMK ID): If you select this option, OSS uses the specified service key to encrypt data in the bucket and records the CMK ID in the metadata of the encrypted object. When a user with decryption permissions downloads the object, the object is automatically decrypted. <cmkname> is an optional alias for the CMK that you specified when you created the key.
Before you use a specified CMK ID, you must create a standard or external key in the same region as the bucket in the KMS console. For more information, see Create a CMK.
Click Save.
Method 2: Set server-side encryption when you upload an object
Method 1: Enable server-side encryption for a bucket
SDKs allow you to enable server-side encryption for existing buckets. You cannot enable server-side encryption when you create a bucket using an SDK. The following code provides examples of how to enable server-side encryption for an existing bucket with common SDKs. For more information about how to enable server-side encryption for an existing bucket with other SDKs, see Introduction to Alibaba Cloud SDKs.
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
// Import the autoloader file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define command line argument descriptions.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located', 'required' => True], // Required. The region where the bucket is located.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // Optional. The domain name that other services can use to access OSS.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // Required. The name of the bucket.
];
// Generate a long options list to parse command line arguments.
$longopts = \array_map(function ($key) {
return "$key:"; // A colon (:) after each parameter indicates that a value is required.
}, array_keys($optsdesc));
// Parse the command line arguments.
$options = getopt("", $longopts);
// Check if required arguments are missing.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Prompt the user that a required argument is missing.
exit(1);
}
}
// Get the command line argument values.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.
// Load credentials (AccessKeyId and AccessKeySecret) from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
// Set the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);
// Set the region.
$cfg->setRegion($region);
// If an endpoint is provided, set the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Create a request object to set the bucket encryption configuration. Use the KMS encryption algorithm and specify SM4 as the data encryption method.
$request = new Oss\Models\PutBucketEncryptionRequest(
bucket: $bucket,
serverSideEncryptionRule: new Oss\Models\ServerSideEncryptionRule(
applyServerSideEncryptionByDefault: new Oss\Models\ApplyServerSideEncryptionByDefault(
sseAlgorithm: 'KMS', // Use the KMS encryption algorithm.
kmsDataEncryption: 'SM4' // The data encryption method is SM4.
))
);
// Call the putBucketEncryption method to set the encryption configuration for the bucket.
$result = $client->putBucketEncryption($request);
// Print the response.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
'request id:' . $result->requestId // The unique identifier of the request.
);
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();
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: Set server-side encryption when you upload an object
The following code provides examples of how to set server-side encryption when you upload an object with common SDKs. For more information about how to set server-side encryption when you upload an object with other SDKs, see Introduction to Alibaba Cloud SDKs.
Java
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.model.ObjectMetadata;
import java.io.File;
public class Put {
public static void main(String[] args) throws Exception {
// Take the China (Hangzhou) region as an example. Specify the actual region.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the region that corresponds to the endpoint. Example: cn-hangzhou.
String region = "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.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the bucket name. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt.
String objectName = "exampledir/exampleobject.txt";
// Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt.
// If you do not specify the full path of the local file, the file is uploaded from the local path that corresponds to the project.
String filePath= "D:\\localpath\\examplefile.txt";
// Create an OSSClient instance.
// When the OSSClient instance is no longer used, call the shutdown method to release resources.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
// Explicitly declare the use of the V4 signature algorithm.
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Create an ObjectMetadata instance and set the server-side encryption method to AES256.
ObjectMetadata metadata = new ObjectMetadata();
metadata.setHeader(OSSHeaders.OSS_SERVER_SIDE_ENCRYPTION, "AES256");
// Create a PutObjectRequest instance.
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));
putObjectRequest.setMetadata(metadata);
// Upload the file.
PutObjectResult result = ossClient.putObject(putObjectRequest);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
PHP
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\Core\OssException;
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
$provider = new EnvironmentVariableCredentialsProvider();
// Set yourEndpoint to the endpoint of the region in which 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.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the bucket name. Example: examplebucket.
$bucket= "examplebucket";
// Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt.
$object = "exampledir/exampleobject.txt";
// Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. If you do not specify the full path of the local file, the file is uploaded from the local path that corresponds to the project.
$filePath = "D:\\localpath\\examplefile.txt";
try{
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
);
$ossClient = new OssClient($config);
$options[OssClient::OSS_HEADERS] = array(
// Set the server-side encryption method to AES256.
"x-oss-server-side-encryption"=>"AES256",
);
// Call the uploadFile method to upload the file and pass the UploadOptions object.
$ossClient->uploadFile($bucket, $object, $filePath, $options);
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . "OK" . "\n");
Node.js
const OSS = require("ali-oss");
const path = require("path");
const client = new OSS({
// Set yourregion to the region in which the bucket is located. For example, if the bucket is 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 bucket name.
bucket: "examplebucket",
});
const headers = {
// Set the server-side encryption method to AES256.
"x-oss-server-side-encryption": "AES256",
};
async function put() {
try {
const result = await client.put(
// Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt.
"exampledir/exampleobject.txt",
// Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. If you do not specify the full path of the local file, the file is uploaded from the local path that corresponds to the project.
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())
# Set yourEndpoint to the endpoint of the region in which 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.
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
# Specify the bucket name.
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. If you do not specify the full path of the local file, the file is uploaded from the local path that corresponds to the project.
local_file_path = 'D:\\examplefile.jpg'
with open(local_file_path, 'rb') as fileobj:
# The seek method specifies that the read and write operations start from the 1,000th byte. When you upload a file, the upload starts from the 1,000th byte and continues until the end of the file.
fileobj.seek(1000, os.SEEK_SET)
# The tell method returns the current position.
current = fileobj.tell()
# Set the server-side encryption method to AES256.
headers = {
'x-oss-server-side-encryption': 'AES256',
}
# Specify the full path of the object. The full path cannot contain the bucket name.
object_key = 'exampledir/object1.jpg'
bucket.put_object(object_key, fileobj, headers=headers)
Go
package main
import (
"fmt"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"os"
)
func main() {
// Obtain access credentials from environment variables. Before you run 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.
// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify the actual region.
client, err := oss.New("https://oss-cn-hangzhou.aliyuncs.com", "", "", oss.SetCredentialsProvider(&provider))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the bucket name. Example: examplebucket.
bucket, err := client.Bucket("examplebucket")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt.
// Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. If you do not specify the full path of the local file, the file is uploaded from the local path that corresponds to the project.
// Set the server-side encryption method to AES256.
err = bucket.PutObjectFromFile("D:\\localpath\\examplefile.txt", "D:\\examplefile.jpg", oss.ServerSideEncryption("AES256"))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
}
Use the ossutil command-line tool
Method 1: Enable server-side encryption for a bucket
You can use the ossutil command-line tool to enable server-side encryption for a bucket. To install ossutil, see Install ossutil.
The following example shows how to set the server-side encryption method to AES256 for an existing bucket named examplebucket.
ossutil api put-bucket-encryption --bucket examplebucket --server-side-encryption-rule "{\"ApplyServerSideEncryptionByDefault\":{\"SSEAlgorithm\":\"AES256\"}}"
Method 2: Set server-side encryption when you upload an object
ossutil lets you specify the server-side encryption method for an object when you upload it. To install ossutil, see Install ossutil. The following example shows how to set the server-side encryption method to AES256 when you upload an object.
Use KMS-managed keys for encryption and decryption
You can use a customer master key (CMK) managed by KMS to generate a data encryption key to encrypt data. Envelope encryption provides an additional layer of security to prevent unauthorized data access. KMS lets you focus on business features, such as data encryption, decryption, and electronic signature verification, without having to invest heavily in ensuring the confidentiality, integrity, and availability of your keys.
The following figure shows the logic of SSE-KMS encryption.
When you use SSE-KMS, you can use the following types of keys:
Use the default KMS key managed by OSS
OSS uses the default KMS CMK to generate different keys to encrypt different objects and automatically decrypts the objects when they are downloaded. When you use this feature for the first time, OSS creates an OSS-managed CMK in KMS.
Configuration methods:
Configure the encryption method for a bucket
Configure the bucket encryption method as KMS, but do not specify a CMK ID. All objects uploaded to this bucket are then encrypted by default.
Configure the encryption method for a destination object
When you upload an object or modify its metadata, include the x-oss-server-side-encryption parameter in the request and set its value to KMS. OSS then uses the default KMS CMK and the AES256 encryption algorithm to encrypt the object. For more information, see PutObject.
Use Bring-Your-Own-Key (BYOK)
After you use BYOK material to generate a CMK in the KMS console, OSS can use the specified KMS CMK to generate different keys to encrypt different objects. The CMK ID is stored in the metadata of the encrypted object. The object is automatically decrypted only when a user with decryption permissions downloads it.
BYOK material can come from two sources:
BYOK material provided by Alibaba Cloud: When you create a key in the KMS console, select KMS for the key material source.
Your own BYOK material: When you create a key in the KMS console, select External for the key material source and import the external key material as required. For more information about how to import external key material, see Import key material.
Configuration methods:
Configure the encryption method for a bucket
Configure the bucket encryption method as KMS and specify a CMK ID. All objects uploaded to this bucket are then encrypted by default.
Configure the destination object encryption method
When you upload an object or modify its metadata, set the x-oss-server-side-encryption parameter to KMS and the x-oss-server-side-encryption-key-id parameter to the specified CMK ID. OSS uses the specified KMS CMK and the AES256 encryption algorithm to encrypt the object. For more information, see PutObject.
Use OSS-managed keys for encryption and decryption
OSS generates and manages data encryption keys and protects them with high-strength, multi-factor security measures. The data is encrypted using the industry-standard Advanced Encryption Standard (AES) 256 algorithms.
Configuration methods:
Configure the encryption method for a bucket
Configure the bucket encryption method as SSE-OSS and specify the encryption algorithm as AES256. All objects uploaded to this bucket are then encrypted by default.
Configure the encryption method for a destination object
When you upload an object or modify its metadata, include the x-oss-server-side-encryption parameter in the request and set its value to AES256. OSS then uses an OSS-managed key to encrypt the object. For more information, see PutObject.
Related API operations
The preceding operations are implemented based on API operations. If your application has high custom requirements, you can directly initiate REST API requests. To directly initiate REST API requests, you must manually write the code to calculate signatures. For more information, see PutBucketEncryption.
FAQ
After I configure an encryption method for a bucket, does OSS encrypt existing objects?
OSS encrypts only the objects that are uploaded after the server-side encryption configuration is enabled. Existing objects are not encrypted. To encrypt existing objects, you can overwrite them using the CopyObject operation.