All Products
Search
Document Center

Object Storage Service:Server-side encryption (Python SDK V2)

Last Updated:Mar 02, 2026

OSS supports server-side encryption for uploaded data. When you upload data, OSS encrypts the data it receives. It then persistently stores this encrypted data. When you download data, OSS automatically decrypts the stored encrypted data and returns the raw data to you. The HTTP request header indicates that the data was server-side encrypted.

Usage notes

  • Before you configure server-side encryption, make sure that you are familiar with this feature. For more information, see Server-side encryption.

  • The sample code in this topic uses the region ID cn-hangzhou of the China (Hangzhou) region. By default, a public endpoint is used. If you want to access OSS from other Alibaba Cloud products in the same region, use an internal endpoint. For more information about the regions and endpoints that OSS supports, see Regions and endpoints.

  • This topic describes how to obtain the credentials for access to OSS from environment variables. For more information about how to configure access credentials, see Configure access credentials.

  • To configure Bucket encryption, you must have the oss:PutBucketEncryption permission. To obtain the Bucket encryption configuration, you must have the oss:GetBucketEncryption permission. To delete the Bucket encryption configuration, you must have the oss:DeleteBucketEncryption permission. For more information, see Grant custom permissions to a RAM user.

Sample code

Configure bucket encryption

Use the following code to set the default encryption method for a bucket. After successful configuration, all objects uploaded to this bucket without a specified encryption method use the bucket's default encryption method:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser to receive user-input parameters.
parser = argparse.ArgumentParser(description="put bucket encryption sample")

# Add command-line argument --region, which indicates the region where the bucket is located. This is a required parameter.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# Add command-line argument --bucket, which indicates the name of the bucket. This is a required parameter.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# Add command-line argument --endpoint, which indicates the domain name that other services use to access OSS. This is an optional parameter.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

# Add command-line argument --sse_algorithm, which indicates the default server-side encryption method. The default value is 'KMS'.
# Valid values: KMS (for KMS encryption), AES256 (for AES-256 encryption), and SM4 (for SM4 encryption algorithm).
parser.add_argument('--sse_algorithm', help='The default server-side encryption method. Valid values: KMS, AES256, and SM4.', default='KMS')

# Add command-line argument --kms_master_key_id, which indicates the master key ID when SSEAlgorithm is set to KMS and a specified CMK is used.
# If a specified CMK is not used, leave this parameter empty.
parser.add_argument('--kms_master_key_id', help='The CMK ID that is specified when SSEAlgorithm is set to KMS and a specified CMK is used for encryption. In other cases, leave this parameter empty.', default='')

# Add command-line argument --kms_data_encryption, which indicates the algorithm used for object encryption.
# The default value is 'SM4'. This parameter is valid only when SSEAlgorithm is set to KMS.
parser.add_argument('--kms_data_encryption', help='The algorithm that is used to encrypt objects. If this parameter is not specified, objects are encrypted using AES256. This parameter is valid only when SSEAlgorithm is set to KMS. Valid value: SM4', default='SM4')

def main():
    # Parse command-line arguments.
    args = parser.parse_args()

    # Load credential information (AccessKeyId and AccessKey Secret) from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the SDK's default configurations.
    cfg = oss.config.load_default()

    # Set the credential provider.
    cfg.credentials_provider = credentials_provider

    # Set the region where the bucket is located.
    cfg.region = args.region

    # If the user provides a custom endpoint, set it in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Initialize the OSS client using the configuration object.
    client = oss.Client(cfg)

    # Call the put_bucket_encryption method to set the bucket's encryption configuration.
    result = client.put_bucket_encryption(
        oss.PutBucketEncryptionRequest(
            bucket=args.bucket,  # Specify the name of the target bucket.
            server_side_encryption_rule=oss.ServerSideEncryptionRule(
                apply_server_side_encryption_by_default=oss.ApplyServerSideEncryptionByDefault(
                    kms_master_key_id=args.kms_master_key_id,  # Master key ID (valid only when SSEAlgorithm is KMS).
                    kms_data_encryption=args.kms_data_encryption,  # Object encryption algorithm (valid only when SSEAlgorithm is KMS).
                    sse_algorithm=args.sse_algorithm,  # Server-side encryption algorithm (e.g., KMS, AES256, or SM4).
                ),
            ),
        )
    )

    # Print the status code and request ID of the operation result.
    print(f'status code: {result.status_code}, '  # HTTP status code, indicating whether the request was successful.
          f'request id: {result.request_id}')     # Request ID, used for tracking request logs and debugging.


if __name__ == "__main__":
    # Program entry point, calls the main function to execute the logic.
    main()

Get bucket encryption configurations

Use the following code to retrieve bucket encryption configurations.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser to receive user input parameters.
parser = argparse.ArgumentParser(description="get bucket encryption sample")

# Add the --region command-line parameter, which specifies the region where the bucket is located. This parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# Add the --bucket command-line parameter, which specifies the name of the bucket. This parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# Add the --endpoint command-line parameter, which specifies the domain names that other services can use to access OSS. This parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse the command-line arguments.
    args = parser.parse_args()

    # Load credential information (AccessKey ID and AccessKey secret) from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK.
    cfg = oss.config.load_default()

    # Set the credentials provider.
    cfg.credentials_provider = credentials_provider

    # Set the region where the bucket is located.
    cfg.region = args.region

    # If the user provides a custom endpoint, set it in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Initialize the OSS client using the configuration object.
    client = oss.Client(cfg)

    # Call the get_bucket_encryption method to retrieve the encryption configuration of the bucket.
    result = client.get_bucket_encryption(
        oss.GetBucketEncryptionRequest(
            bucket=args.bucket,  # Specify the name of the target bucket.
        )
    )

    # Print the status code and request ID of the operation result.
    print(f'status code: {result.status_code}, '
          f'request id: {result.request_id}, '
    )


if __name__ == "__main__":
    # Entry point of the program. Call the main function to execute the logic.
    main()

Delete bucket encryption configurations

Use the following code to delete bucket encryption configurations.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser to receive user input.
parser = argparse.ArgumentParser(description="delete bucket encryption sample")

# Add the --region command-line argument. This specifies the region where the bucket is located. It is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# Add the --bucket command-line argument. This specifies the name of the bucket. It is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# Add the --endpoint command-line argument. This specifies the domain names that other services can use to access OSS. It is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse command-line arguments.
    args = parser.parse_args()

    # Load access credentials (AccessKeyId and AccessKeySecret) from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the SDK's default configurations.
    cfg = oss.config.load_default()

    # Set the credential provider.
    cfg.credentials_provider = credentials_provider

    # Set the region where the bucket is located.
    cfg.region = args.region

    # If a custom endpoint is provided, set it in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Initialize the OSS client using the configuration object.
    client = oss.Client(cfg)

    # Call the delete_bucket_encryption method to delete the bucket's encryption configuration.
    result = client.delete_bucket_encryption(
        oss.DeleteBucketEncryptionRequest(
            bucket=args.bucket,  # Specify the name of the target bucket.
        )
    )

    # Print the status code and request ID of the operation result.
    print(f'status code: {result.status_code}, '  # HTTP status code, indicates if the request was successful.
          f'request id: {result.request_id}')     # Request ID, used for tracking requests.


if __name__ == "__main__":
    # Program entry point. Call the main function to execute the logic.
    main()

References

  • For more information about the API operation for configuring server-side encryption, see PutBucketEncryption.

  • For more information about the API operation for obtaining the server-side encryption configuration, see GetBucketEncryption.

  • For more information about the API operation for deleting the server-side encryption configuration, see DeleteBucketEncryption.