Object Storage Service (OSS) supports server-side encryption to protect data at rest. When enabled, OSS encrypts objects on upload and decrypts them on download. The x-oss-server-side-encryption header in the download response confirms that the object is encrypted. For more information, see GetObject.
Choose an encryption method
OSS provides two server-side encryption methods. Both support the AES-256 algorithm. SSE-KMS also supports SM4 when used through SDKs.
| Dimension | SSE-KMS | SSE-OSS |
|---|---|---|
| Key management | A customer master key (CMK) managed by Key Management Service (KMS). Use a default CMK or specify your own | OSS generates and manages all keys |
| Key control | You control the CMK. Optionally bring your own key material (BYOK) | No manual key management required |
| Encryption scope | Object data only. The data key is encrypted and stored in the object metadata | Object data. Each object is encrypted with a unique key protected by master keys |
| Cost | KMS API charges apply. For details, see Billing of KMS | Free |
| Best for | Workloads that require specific CMKs for security and compliance | Workloads that need encryption without manual key management |
How SSE-KMS works
SSE-KMS uses envelope encryption. KMS generates a data key to encrypt the object, then encrypts the data key with the CMK. The encrypted data key is stored in the object metadata.
Default KMS-managed CMK
On first use of SSE-KMS, OSS creates a default CMK in KMS and uses keys derived from it to encrypt and decrypt objects.
To configure:
Bucket level: Set the encryption method to KMS without specifying a CMK ID. All objects uploaded to the bucket are encrypted.
Object level: Set the
x-oss-server-side-encryptionheader toKMSin your upload request. OSS uses the default CMK and AES-256 to encrypt the object. For more information, see PutObject.
Custom CMK (bring your own key)
A custom CMK gives you full control over the encryption key. The CMK ID is recorded in the object metadata, and only users with decryption permissions can download the object.
Key material sources:
Alibaba Cloud KMS: Select Alibaba Cloud KMS as the key material source when creating a key in KMS.
External key material: Select External as the key material source and import your own key material. For more information, see Import key material.
To configure:
Bucket level: Set the encryption method to KMS and specify a CMK ID. All objects uploaded to the bucket are encrypted with the specified CMK.
Object level: Set
x-oss-server-side-encryptiontoKMSandx-oss-server-side-encryption-key-idto the CMK ID in your upload request. For more information, see PutObject.
How SSE-OSS works
SSE-OSS encrypts each object with a unique AES-256 data key. OSS generates and manages these data keys and protects them with master keys.
To configure:
Bucket level: Set the encryption method to SSE-OSS with AES-256. All objects uploaded to the bucket are encrypted by default.
Object level: Set the
x-oss-server-side-encryptionheader toAES256in your upload request. For more information, see PutObject.
Usage notes
Changing the encryption method of a bucket does not affect existing objects. To encrypt existing objects, call CopyObject to overwrite them with the current encryption method.
An object can be encrypted by only one method at a time.
Object-level encryption takes precedence over bucket-level encryption. If you specify an encryption method when uploading or copying an object, that method overrides the bucket default. For more information, see PutObject.
Objects obtained through mirroring-based back-to-origin rules are not encrypted by default.
SSE-KMS requires permissions on the specified CMK. Anonymous requests or requests without proper KMS permissions fail with the error
This request is forbidden by kms.
Key rotation
Server-side encryption supports KMS key rotation if you have purchased the key rotation service.
After a key rotation or encryption key update:
The new key applies only to objects created after the rotation. Existing objects remain encrypted with the previous key.
Never delete old keys after a key update. Deleting old keys prevents access to objects encrypted with those keys.
Required permissions
RAM users need specific permissions for each encryption operation. For more information about granting permissions, see Attach a custom policy to a RAM user.
Permissions per operation
| Operation | Required permissions | Additional KMS permissions (SSE-KMS with a specific CMK) |
|---|---|---|
| Configure bucket encryption | Bucket management, PutBucketEncryption, GetBucketEncryption | ListKeys, ListAliases, ListAliasesByKeyId, DescribeKey |
| Upload objects | Object upload | ListKeys, ListAliases, ListAliasesByKeyId, DescribeKey, GenerateDataKey, Decrypt |
| Download objects | Object access | Decrypt |
RAM policy examples
The following examples grant KMS permissions through RAM policies.
Configure bucket encryption (SSE-KMS with a specific CMK)
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"kms:List*",
"kms:DescribeKey"
],
"Resource": [
"acs:kms:*:141661496593****:*"
]
}
]
}Replace the resource ARN with your account ID. To restrict access to a specific CMK, replace the wildcard with the CMK ID.
Upload objects (SSE-KMS with a specific CMK)
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"kms:List*",
"kms:DescribeKey",
"kms:GenerateDataKey",
"kms:Decrypt"
],
"Resource": [
"acs:kms:*:141661496593****:*"
]
}
]
}Download objects (SSE-KMS with a specific CMK)
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"kms:Decrypt"
],
"Resource": [
"acs:kms:*:141661496593****:*"
]
}
]
}Enable server-side encryption
If you have purchased the key rotation service of KMS, server-side encryption supports KMS key rotation. After key rotation is enabled, the new key applies only to objects created after the rotation. Existing objects remain encrypted with the previous key.
After updating the encryption key, the new key applies only to objects written after the update. Never delete old keys after a key update. Deleting old keys affects access to existing objects.
OSS console
Enable encryption for a bucket
When creating a bucket
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, click Create Bucket.
In the Create Bucket panel, configure the encryption parameters. For more information about other parameters, see Create a bucket.
Parameter Description Encryption Method Select the encryption method. Valid values: None (server-side encryption is disabled), OSS-Managed (OSS-managed keys encrypt objects in the bucket. Each object is encrypted with a different key, and master keys protect those keys), KMS (the default KMS-managed CMK or a specific CMK encrypts and decrypts objects. To use KMS, activate KMS first. For more information, see Activate KMS). Encryption Algorithm Only AES-256 is supported. CMK Available only when KMS is selected for Encryption Method. The CMK format is <alias>(CMK ID). Valid values: alias/acs/oss(CMK ID) (the default CMK encrypts objects and automatically decrypts them on download), alias/\<cmkname\>(CMK ID) (a custom CMK encrypts objects. The CMK ID is recorded in the object metadata. Objects are automatically decrypted for users with decryption permissions. Before specifying a CMK ID, create a normal key or an external key in the same region as the bucket. For more information, see Create a CMK).Click Create. In the confirmation dialog, click Confirm.
For an existing bucket
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the target bucket.
In the left-side navigation tree, choose Content Security > Server-side Encryption.
On the Server-side Encryption page, click Settings and configure the parameters.
Parameter Description Encryption Method Select the encryption method. Valid values: None (server-side encryption is disabled), OSS-Managed (OSS-managed keys encrypt objects in the bucket. Each object is encrypted with a different key, and master keys protect those keys), KMS (the default KMS-managed CMK or a specific CMK encrypts and decrypts objects. To use KMS, activate KMS first. For more information, see Activate KMS). Encryption Algorithm Only AES-256 is supported. CMK Available only when KMS is selected for Encryption Method. The CMK format is <alias>(CMK ID). Valid values: OSS automatically creates a key by default (the default CMK encrypts objects and automatically decrypts them on download. The CMK format isalias/acs/oss(CMK ID). View the CMK in the KMS console.NoteUpload at least one object to the bucket before viewing the CMK in the KMS console, so the CMK is created and applied), alias/\<cmkname\>(CMK ID) (a custom CMK encrypts objects in the bucket. The CMK ID is recorded in the object metadata. Objects are automatically decrypted for users with decryption permissions. Before specifying a CMK ID, create a normal key or an external key in the same region as the bucket. For more information, see Create a CMK).
Click Save.
Enable encryption when uploading an object
For more information, see Simple upload.
OSS SDKs
Enable encryption for a bucket
OSS SDKs support enabling server-side encryption for existing buckets only. For other programming languages, see Overview.
Java
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
<?php
// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Specify descriptions for command line parameters.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
];
// Generate a long options list to parse the command line parameters.
$longopts = \array_map(function ($key) {
return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));
// Parse the command line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Specify that the required parameters are not configured.
exit(1);
}
}
// Obtain the values of the command line parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Use environment variables to load the AccessKey ID and AccessKey secret.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);
// Specify the region.
$cfg->setRegion($region);
// Specify the endpoint if an endpoint is provided.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Create a PutBucketEncryptionRequest object, use the Key Management Service (KMS) encryption method, and set the encryption algorithm to SM4.
$request = new Oss\Models\PutBucketEncryptionRequest(
bucket: $bucket,
serverSideEncryptionRule: new Oss\Models\ServerSideEncryptionRule(
applyServerSideEncryptionByDefault: new Oss\Models\ApplyServerSideEncryptionByDefault(
sseAlgorithm: 'KMS', //Use the KMS encryption method.
kmsDataEncryption: 'SM4' // Set the encryption algorithm to SM4.
))
);
// Use the putBucketEncryption method to configure the server-side encryption configurations for the bucket.
$result = $client->putBucketEncryption($request);
// Display the returned result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The returned HTTP status code.
'request id:' . $result->requestId // The request ID of the request, which is the unique identifier of the request.
);Node.js
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();C#
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);
}Go
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")
}C++
#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. Specify the endpoint of the region in which the bucket is located. */
std::string Endpoint = "yourEndpoint";
/* 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.*/
std::string Region = "yourRegion";
/* Specify the name of the bucket. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* 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);
client.SetRegion(Region);
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;
}Enable encryption when uploading an object
The following examples set server-side encryption when uploading an object. For other programming languages, see Overview.
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 {
// Specify an endpoint based on the region of your bucket.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the ID of the region of the your bucket.
String region = "cn-hangzhou";
// Obtain access credentials. 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.
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 path of the local file. Example: D:\\localpath\\examplefile.txt.
// If you do not specify a local file path, the file in the local path in which the demo project belongs is uploaded.
String filePath= "D:\\localpath\\examplefile.txt";
// Create an OSS client instance.
// When the client instance is no longer used, call the shutdown method to release resources.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
// Use the signature algorithm V4.
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Create an ObjectMetadata object and set the server 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 an 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 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.
$object = "exampledir/exampleobject.txt";
// Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. If the path of the local file is not specified, 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.
"exampledir/exampleobject.txt",
// Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. If the path of the local file is not specified, 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. If the path of the local file is not specified, 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.
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.
// Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. If the path of the local file is not specified, 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)
}
}ossutil
Enable encryption for a bucket
ossutil allows you to enable server-side encryption for a bucket. For installation instructions, see Install ossutil.
The following example sets AES-256 encryption for a bucket named examplebucket:
ossutil api put-bucket-encryption --bucket examplebucket --server-side-encryption-rule "{\"ApplyServerSideEncryptionByDefault\":{\"SSEAlgorithm\":\"AES256\"}}"For more information, see put-bucket-encryption.
Enable encryption when uploading an object
ossutil allows you to set server-side encryption when uploading an object. For installation instructions, see Install ossutil.
The following example uploads a file with AES-256 encryption:
ossutil cp examplefile.txt oss://examplebucket --metadata=x-oss-server-side-encryption:AES256For more information, see cp.
OSS API
To integrate server-side encryption directly into your application, call the RESTful API. Include the signature calculation in your code. For more information, see PutBucketEncryption.
FAQ
Does OSS encrypt existing objects after I enable server-side encryption for a bucket?
No. OSS encrypts only objects uploaded after server-side encryption is enabled. To encrypt existing objects, call CopyObject to overwrite them with the current encryption method.