Tüm Ürünler
Search
Belge Merkezi

Object Storage Service:Server-side encryption

Son Güncelleme:Oct 01, 2026

Sunucu tarafı şifreleme etkinleştirilmiş bir pakete nesne yüklediğinizde, Object Storage Service (OSS) nesneyi depolamadan önce şifreler. GetObject isteği kullanarak nesneyi indirdiğinizde, OSS nesnenin şifresini otomatik olarak çözer ve size döndürür. Yanıttaki x-oss-server-side-encryption üst bilgisi, nesnenin sunucu tarafında şifrelendiğini gösterir.

Not

x-oss-server-side-encryption yanıt üst bilgisi hakkında daha fazla bilgi için bkz. GetObject.

Senaryolar

OSS, sunucu tarafı şifreleme yoluyla durumdaki veriler için koruma sağlar. Bu özellik; derin öğrenme örnek dosyalarının veya çevrimiçi ortak çalışma belgesi verilerinin depolanması gibi, veri depolama için yüksek güvenlik veya uyumluluk gereksinimleri olan uygulamalar için uygundur.

Şifreleme yöntemleri

OSS, farklı senaryolar için iki sunucu tarafı şifreleme yöntemi sunar. Gereksinimlerinize göre bir yöntem seçebilirsiniz.

Şifreleme yöntemi

Açıklama

Senaryolar

Notlar

Faturalama

Key Management Service (KMS) tarafından yönetilen anahtarları kullanarak verileri şifreleme ve şifresini çözme (SSE-KMS)

KMS tarafından yönetilen varsayılan müşteri ana master anahtarını (CMK) veya belirtilen bir CMK'yı kullanarak verileri şifreleyin ve şifresini çözün. Veriler, KMS sunucusuna ağ üzerinden gönderilmeden şifrelenir ve şifresi çözülür.

Bu yöntem, güvenlik ve uyumluluk amaçlarıyla belirtebileceğiniz kendi yönettiğiniz anahtarları kullanmanız gereken senaryolar içindir.

  • Bir nesneyi şifrelemek için kullanılan anahtar da şifrelenir ve nesnenin meta verilerinde saklanır.

  • SSE-KMS şifreleme yöntemi yalnızca nesne verilerini şifreler, nesnenin meta verilerini şifrelemez.

  • OSS konsolunda varsayılan olarak oluşturulan KMS anahtarı ücretsizdir.

  • Kendi KMS anahtarınızı kullanırsanız, KMS'de ücretlere tabi olursunuz. Daha fazla bilgi için bkz. KMS fiyatlandırması.

OSS tarafından yönetilen anahtarları kullanarak verileri şifreleme ve şifresini çözme (SSE-OSS)

Her nesneyi şifrelemek için tamamen OSS tarafından yönetilen bir anahtar kullanın. Gelişmiş güvenlik için OSS, veri şifreleme anahtarının kendisini şifrelemek üzere bir master anahtar da kullanır.

Bu yöntem, yalnızca temel şifrelemeye ihtiyacınız olduğu ve anahtarları yönetmeniz gerekmediği senaryolar içindir.

Yok.

Ücretsiz.

Notlar

  • SSE-KMS şifrelemesi etkinleştirilmiş bir paketteki nesneleri yüklerken, indirirken veya erişirken, belirtilen CMK ID'sini kullanma izniniz olduğundan ve isteğin anonim olmadığından emin olun. Aksi takdirde, istek başarısız olur ve This request is forbidden by kms hatası döndürülür.

  • Yansıtma tabanlı geri kaynağa gitme kullanılarak bir pakete yansıtılan nesneler varsayılan olarak şifrelenmez.

  • Bir paket için şifreleme yöntemini etkinleştirmek veya değiştirmek, paketteki mevcut nesnelerin şifreleme yapılandırmasını etkilemez.

  • Bir nesne için aynı anda yalnızca bir sunucu tarafı şifreleme yöntemi kullanılabilir.

  • Bir paket için şifreleme yapılandırırsanız, bir nesneyi yüklerken veya kopyalarken yine de o nesne için farklı bir şifreleme yöntemi belirtebilirsiniz. Nesne için belirtilen şifreleme yöntemi geçerli olur. Daha fazla bilgi için bkz. PutObject.

İzinler

Aşağıdaki listede, farklı senaryolarda sunucu tarafı şifrelemeyi kullanmak için bir Resource Access Management (RAM) kullanıcısının ihtiyaç duyduğu izinler açıklanmaktadır.

Not

Bir RAM kullanıcısına nasıl izin verileceği hakkında daha fazla bilgi için bkz. RAM kullanıcısına özel izinler verme.

  • Bir paket için şifreleme yöntemini yapılandırma

    • Hedef paket üzerindeki yönetim izinleri.

    • PutBucketEncryption ve GetBucketEncryption izinleri.

    • Şifreleme yöntemini SSE-KMS olarak ayarlar ve bir CMK ID'si belirtirseniz, ListKeys, ListAliases, ListAliasesByKeyId ve DescribeKey izinleri de gereklidir. Bu senaryo için örnek bir RAM ilkesi aşağıda verilmiştir:

      {
        "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.
            ]
          }
        ]
      }
  • Şifrelenmiş bir pakete nesne yükleme

    • Hedef pakete nesne yükleme izinleri.

    • Şifreleme yöntemi KMS olarak ayarlanmışsa ve bir CMK ID'si belirtilmişse, ListKeys, ListAliases, ListAliasesByKeyId, DescribeKey, GenerateDataKey ve Decrypt izinleri de gereklidir. Bu senaryo için örnek bir RAM ilkesi aşağıda verilmiştir:

      {
        "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.
            ]
          }
        ]
      }
  • Şifrelenmiş bir paketten nesne indirme

    • Hedef paketteki nesnelere erişim izinleri.

    • Şifreleme yöntemi KMS olarak ayarlanmışsa ve bir CMK ID'si belirtilmişse, Decrypt izni de gereklidir. Bu senaryo için örnek bir RAM ilkesi aşağıda verilmiştir:

      {
        "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.
            ]
          }
        ]
      }

Yordamlar

Önemli
  • KMS için anahtar döndürme ek hizmetini satın alırsanız, sunucu tarafı şifreleme KMS anahtarları için anahtar döndürmeyi destekler. Anahtar döndürme etkinleştirildikten sonra, yeni anahtar yalnızca yeni yüklenen nesneleri şifrelemek için kullanılır. Mevcut nesnelerin şifreleme anahtarları değişmez.

  • OSS'deki KMS şifreleme anahtarını güncellerseniz, yeni anahtar yalnızca yeni yüklenen nesneleri şifrelemek için kullanılır. Anahtar güncellemesinden önce yüklenen nesneler hala eski anahtarla şifrelenir. Bu nedenle, güncellemeden sonra eski anahtarı silmeyin. Aksi takdirde, mevcut nesnelere erişemezsiniz.

OSS konsolunu kullanma

Yöntem 1: Bir paket için sunucu tarafı şifrelemeyi etkinleştirme

Paket oluştururken sunucu tarafı şifrelemeyi etkinleştirme

  1. OSS konsolunda oturum açın.

  2. Buckets öğesini tıklayın ve ardından Create Bucket öğesini tıklayın.

  3. Create Bucket panelinde aşağıdaki parametreleri yapılandırın.

    Aşağıdaki parametreler, bir bölge için sunucu tarafı şifrelemeyi yapılandırmak için kullanılır:

    Parametre

    Açıklama

    Encryption Method

    Nesneler için bir şifreleme yöntemi seçin. Geçerli değerler:

    • None: Sunucu tarafı şifreleme devre dışı bırakılır.

    • SSE-OSS: Şifreleme için OSS tarafından yönetilen anahtarları kullanın. OSS, her nesneyi şifrelemek için farklı bir anahtar kullanır. Ek koruma için OSS, veri şifreleme anahtarının kendisini şifrelemek üzere bir master anahtar kullanır.

    • SSE-KMS: Şifreleme ve şifre çözme için KMS tarafından yönetilen varsayılan CMK'yı veya belirtilen bir CMK'yı kullanın.

      SSE-KMS'yi kullanmadan önce KMS'yi etkinleştirmeniz gerekir. Daha fazla bilgi için bkz. Özel KMS örneği satın alma.

    Encryption Algorithm

    Yalnızca AES256 şifreleme algoritmasını destekler.

    CMK

    Sunucu tarafı şifreleme için KMS seçtiğinizde yalnızca bu seçeneği yapılandırmanız gerekir.

    Bir şifreleme anahtarı seçin. Anahtar <alias>(CMK ID) biçimindedir. <alias>, CMK'nın takma adıdır ve CMK ID, CMK'nın kimliğidir. Geçerli değerler:

    • alias/acs/oss(CMK ID): Bu seçeneği belirlerseniz, OSS paketteki verileri şifrelemek için varsayılan hizmet anahtarını kullanır ve paketten nesneleri indirdiğinizde verilerin şifresini otomatik olarak çözer.

    • alias/<cmkname>(CMK ID): Bu seçeneği belirlerseniz, OSS paketteki verileri şifrelemek için belirtilen hizmet anahtarını kullanır ve CMK ID'sini şifrelenmiş nesnenin meta verilerine kaydeder. Şifre çözme izni olan bir kullanıcı nesneyi indirdiğinde, nesnenin şifresi otomatik olarak çözülür. <cmkname>, anahtarı oluşturduğunuzda belirttiğiniz CMK için isteğe bağlı bir takma addır.

      Belirtilen bir CMK ID'sini kullanmadan önce, KMS konsolunda paketle aynı bölgede standart veya harici bir anahtar oluşturmanız gerekir. Daha fazla bilgi için bkz. CMK oluşturma.

    Diğer parametreler hakkında daha fazla bilgi için bkz. Paket oluşturma.

  4. OK öğesini tıklayın.

Mevcut bir paket için sunucu tarafı şifrelemeyi etkinleştirme

  1. OSS konsolunda oturum açın.

  2. Sol gezinme bölmesinde, Buckets öğesini tıklayın. Buckets sayfasında, istediğiniz paketi bulun ve tıklayın.

  3. Soldaki gezinme bölmesinde, Content Security > Server-side Encryption seçeneklerini belirleyin.

  4. Server-side Encryption sayfasında, Configure öğesini tıklayın ve parametreleri yapılandırın.

    Parametre

    Açıklama

    Encryption Method

    Nesneler için bir şifreleme yöntemi seçin. Geçerli değerler:

    • None: Sunucu tarafı şifreleme devre dışı bırakılır.

    • SSE-OSS: Şifreleme için OSS tarafından yönetilen anahtarları kullanın. OSS, her nesneyi şifrelemek için farklı bir anahtar kullanır. Ek koruma için OSS, veri şifreleme anahtarının kendisini şifrelemek üzere bir master anahtar kullanır.

    • SSE-KMS: Şifreleme ve şifre çözme için KMS tarafından yönetilen varsayılan CMK'yı veya belirtilen bir CMK'yı kullanın.

      SSE-KMS'yi kullanmadan önce KMS'yi etkinleştirmeniz gerekir. Daha fazla bilgi için bkz. Özel KMS örneği satın alma.

    Encryption Algorithm

    Yalnızca AES256 şifreleme algoritması desteklenir.

    CMK

    Bu parametre yalnızca Encryption Method öğesini SSE-KMS olarak ayarladığınızda gereklidir.

    Bir şifreleme anahtarı seçin. Anahtar <alias>(CMK ID) biçimindedir. <alias>, CMK'nın takma adıdır ve CMK ID, CMK'nın kimliğidir. Geçerli değerler:

    • Default Service Key: Bu seçeneği belirlerseniz, OSS paketteki verileri şifrelemek için varsayılan bir hizmet anahtarı oluşturur ve paketten nesneleri indirdiğinizde verilerin şifresini otomatik olarak çözer. OSS tarafından oluşturulan varsayılan hizmet anahtarı alias/acs/oss (CMK ID) biçimindedir. Bu hizmet anahtarını KMS konsolunda görüntüleyebilirsiniz.

      Not

      Bu hizmet anahtarını KMS konsolunda görüntüleyebilmeniz için, karşılık gelen şifreleme anahtarının oluşturulduğundan ve OSS hizmetinizle ilişkilendirildiğinden emin olmak üzere hedef pakete en az bir nesne yüklemeniz gerekir.

    • alias/<cmkname>(CMK ID): Bu seçeneği belirlerseniz, OSS paketteki verileri şifrelemek için belirtilen hizmet anahtarını kullanır ve CMK ID'sini şifrelenmiş nesnenin meta verilerine kaydeder. Şifre çözme izni olan bir kullanıcı nesneyi indirdiğinde, nesnenin şifresi otomatik olarak çözülür. <cmkname>, anahtarı oluşturduğunuzda belirttiğiniz CMK için isteğe bağlı bir takma addır.

      Belirtilen bir CMK ID'sini kullanmadan önce, KMS konsolunda paketle aynı bölgede standart veya harici bir anahtar oluşturmanız gerekir. Daha fazla bilgi için bkz. CMK oluşturma.

  5. Save öğesini tıklayın.

Yöntem 2: Bir nesne yüklerken sunucu tarafı şifrelemeyi ayarlama

Daha fazla bilgi için bkz. Basit yükleme.

Alibaba Cloud SDK'larını kullanma

Yöntem 1: Bir paket için sunucu tarafı şifrelemeyi etkinleştirme

SDK'lar, mevcut paketler için sunucu tarafı şifrelemeyi etkinleştirmenize olanak tanır. Bir SDK kullanarak paket oluştururken sunucu tarafı şifrelemeyi etkinleştiremezsiniz. Aşağıdaki kod, yaygın SDK'larla mevcut bir paket için sunucu tarafı şifrelemeyi nasıl etkinleştireceğinize ilişkin örnekler sağlar. Diğer SDK'larla mevcut bir paket için sunucu tarafı şifrelemeyi nasıl etkinleştireceğiniz hakkında daha fazla bilgi için bkz. Alibaba Cloud SDK'larına giriş.

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;
}

Yöntem 2: Bir nesne yüklerken sunucu tarafı şifrelemeyi ayarlama

Aşağıdaki kod, yaygın SDK'larla bir nesne yüklerken sunucu tarafı şifrelemeyi nasıl ayarlayacağınıza ilişkin örnekler sağlar. Diğer SDK'larla bir nesne yüklerken sunucu tarafı şifrelemeyi nasıl ayarlayacağınız hakkında daha fazla bilgi için bkz. Alibaba Cloud SDK'larına giriş.

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)
	}
}

ossutil komut satırı aracını kullanma

Yöntem 1: Bir paket için sunucu tarafı şifrelemeyi etkinleştirme

Bir paket için sunucu tarafı şifrelemeyi etkinleştirmek üzere ossutil komut satırı aracını kullanabilirsiniz. ossutil'i yüklemek için bkz. ossutil yükleme.

Aşağıdaki örnek, examplebucket adlı mevcut bir paket için sunucu tarafı şifreleme yöntemini AES256 olarak nasıl ayarlayacağınızı gösterir.

ossutil api put-bucket-encryption --bucket examplebucket --server-side-encryption-rule "{\"ApplyServerSideEncryptionByDefault\":{\"SSEAlgorithm\":\"AES256\"}}"

Bu komut hakkında daha fazla bilgi için bkz. put-bucket-encryption.

Yöntem 2: Bir nesne yüklerken sunucu tarafı şifrelemeyi ayarlama

ossutil, bir nesneyi yüklerken sunucu tarafı şifreleme yöntemini belirtmenize olanak tanır. ossutil'i yüklemek için bkz. ossutil yükleme. Aşağıdaki örnek, bir nesne yüklerken sunucu tarafı şifreleme yöntemini AES256 olarak nasıl ayarlayacağınızı gösterir.

ossutil cp examplefile.txt oss://examplebucket --metadata=x-oss-server-side-encryption:AES256

Bu komut hakkında daha fazla bilgi için bkz. cp (nesneleri yükleme).

Şifreleme ve şifre çözme için KMS tarafından yönetilen anahtarları kullanma

Verileri şifrelemek üzere bir veri şifreleme anahtarı oluşturmak için KMS tarafından yönetilen bir müşteri ana master anahtarı (CMK) kullanabilirsiniz. Zarf şifreleme, yetkisiz veri erişimini önlemek için ek bir güvenlik katmanı sağlar. KMS, anahtarlarınızın gizliliğini, bütünlüğünü ve kullanılabilirliğini sağlamak için yoğun yatırımlar yapmanıza gerek kalmadan veri şifreleme, şifre çözme ve elektronik imza doğrulama gibi iş özelliklerine odaklanmanıza olanak tanır.

Aşağıdaki şekil, SSE-KMS şifrelemenin mantığını gösterir.

image

SSE-KMS kullanırken aşağıdaki anahtar türlerini kullanabilirsiniz:

  • OSS tarafından yönetilen varsayılan KMS anahtarını kullanma

    OSS, farklı nesneleri şifrelemek üzere farklı anahtarlar oluşturmak için varsayılan KMS CMK'sını kullanır ve nesneler indirildiğinde bunların şifresini otomatik olarak çözer. Bu özelliği ilk kez kullandığınızda, OSS KMS'de OSS tarafından yönetilen bir CMK oluşturur.

    Yapılandırma yöntemleri:

    • Bir paket için şifreleme yöntemini yapılandırma

      Paket şifreleme yöntemini KMS , ancak bir CMK ID'si belirtmeyin. Bu pakete yüklenen tüm nesneler varsayılan olarak şifrelenir.

    • Bir hedef nesne için şifreleme yöntemini yapılandırma

      Bir nesne yüklerken veya meta verilerini değiştirirken, istekte x-oss-server-side-encryption parametresini dahil edin ve değerini KMS olarak ayarlayın. OSS daha sonra varsayılan KMS CMK'sını ve AES256 şifreleme algoritmasını kullanarak nesneyi şifreler. Daha fazla bilgi için bkz. PutObject.

  • Bring-Your-Own-Key (BYOK) kullanma

    KMS konsolunda BYOK materyalini kullanarak bir CMK oluşturduktan sonra, OSS farklı nesneleri şifrelemek üzere farklı anahtarlar oluşturmak için belirtilen KMS CMK'sını kullanabilir. CMK ID'si, şifrelenmiş nesnenin meta verilerinde saklanır. Nesnenin şifresi yalnızca şifre çözme izni olan bir kullanıcı onu indirdiğinde otomatik olarak çözülür.

    BYOK materyali iki kaynaktan gelebilir:

    • Alibaba Cloud tarafından sağlanan BYOK materyali: KMS konsolunda bir anahtar oluştururken, anahtar materyali kaynağı olarak KMS öğesini seçin.

    • Kendi BYOK materyaliniz: KMS konsolunda bir anahtar oluştururken, anahtar materyali kaynağı olarak External öğesini seçin ve harici anahtar materyalini gerektiği şekilde içe aktarın. Harici anahtar materyalini nasıl içe aktaracağınız hakkında daha fazla bilgi için bkz. Anahtar materyali içe aktarma.

    Yapılandırma yöntemleri:

    • Bir paket için şifreleme yöntemini yapılandırma

      Paket şifreleme yöntemini KMS ve bir CMK ID'si belirtin. Bu pakete yüklenen tüm nesneler varsayılan olarak şifrelenir.

    • Hedef nesne şifreleme yöntemini yapılandırma

      Bir nesne yüklerken veya meta verilerini değiştirirken, x-oss-server-side-encryption parametresini KMS ve x-oss-server-side-encryption-key-id parametresini belirtilen CMK ID'sine ayarlayın. OSS, belirtilen KMS CMK'sını ve AES256 şifreleme algoritmasını kullanarak nesneyi şifreler. Daha fazla bilgi için bkz. PutObject.

Şifreleme ve şifre çözme için OSS tarafından yönetilen anahtarları kullanma

OSS, veri şifreleme anahtarlarını oluşturur ve yönetir ve bunları yüksek güçlü, çok faktörlü güvenlik önlemleriyle korur. Veriler, endüstri standardı Gelişmiş Şifreleme Standardı (AES) 256 algoritmaları kullanılarak şifrelenir.

Yapılandırma yöntemleri:

  • Bir paket için şifreleme yöntemini yapılandırma

    Paket şifreleme yöntemini SSE-OSS olarak yapılandırın ve şifreleme algoritmasını AES256 olarak belirtin. Bu pakete yüklenen tüm nesneler varsayılan olarak şifrelenir.

  • Bir hedef nesne için şifreleme yöntemini yapılandırma

    Bir nesne yüklerken veya meta verilerini değiştirirken, istekte x-oss-server-side-encryption parametresini dahil edin ve değerini AES256 olarak ayarlayın. OSS daha sonra OSS tarafından yönetilen bir anahtar kullanarak nesneyi şifreler. Daha fazla bilgi için bkz. PutObject.

İlgili API işlemleri

Yukarıdaki işlemler API işlemlerine dayanarak uygulanır. Uygulamanız yüksek düzeyde özel gereksinimlere sahipse, doğrudan REST API istekleri başlatabilirsiniz. Doğrudan REST API istekleri başlatmak için, imzaları hesaplamak üzere kodu manuel olarak yazmanız gerekir. Daha fazla bilgi için bkz. PutBucketEncryption.

SSS

Bir paket için bir şifreleme yöntemi yapılandırdıktan sonra, OSS mevcut nesneleri şifreler mi?

OSS, yalnızca sunucu tarafı şifreleme yapılandırması etkinleştirildikten sonra yüklenen nesneleri şifreler. Mevcut nesneler şifrelenmez. Mevcut nesneleri şifrelemek için, CopyObject işlemini kullanarak bunların üzerine yazabilirsiniz.