El contenido no se encuentra disponible en el idioma seleccionado. Estamos trabajando continuamente para agregar más idiomas. Gracias por su apoyo.

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

Server-Side Encryption (SDK for Python)

Updated on 2024-11-26 GMT+08:00

Function

This API configures server-side encryption for objects, so that they will be encrypted or decrypted when you upload them to or download them from a bucket.

The encryption and decryption happen on the server side.

There are different encryption methods for you to choose from. Available encryption methods include server-side encryption with KMS-managed keys (SSE-KMS) and server-side encryption with customer-provided keys (SSE-C). Both of the two methods use the AES-256 algorithm.

With SSE-KMS, OBS uses the keys provided by KMS for server-side encryption.

With SSE-C, OBS uses the keys and MD5 values provided by customers for server-side encryption.

When server-side encryption is used, the returned ETag value is not the object's MD5 value. OBS will verify the object's MD5 value as long as the upload request includes the Content-MD5 header, no matter whether server-side encryption is used or not.

For more information, see Server-Side Encryption.

Restrictions

Method

ObsClient.putFile(bucketName, objectKey, file_path, metadata, headers, extensionHeaders)

Supported APIs

The following table lists APIs related to server-side encryption:

Method in OBS SDK for Python

Description

Supported Encryption Method

ObsClient.putContent

Sets the encryption algorithm and key during object upload to enable server-side encryption.

SSE-KMS

SSE-C

ObsClient.putFile

Sets the encryption algorithm and key during file upload to enable server-side encryption.

SSE-KMS

SSE-C

ObsClient.getObject

Sets the decryption algorithm and key during object download to decrypt the object.

SSE-C

ObsClient.copyObject

  1. Sets the decryption algorithm and key for decrypting the source object during object copy.
  2. Sets the encryption algorithm and key during object copy to enable the encryption algorithm for the target object.

SSE-KMS

SSE-C

ObsClient.getObjectMetadata

Sets the decryption algorithm and key when obtaining the object metadata to decrypt the object.

SSE-C

ObsClient.initiateMultipartUpload

Sets the encryption algorithm and key when initializing a multipart upload task to enable server-side encryption for the final object generated.

SSE-KMS

SSE-C

ObsClient.uploadPart

Sets the encryption algorithm and key during multipart upload to enable server-side encryption for parts.

SSE-C

ObsClient.copyPart

  1. Sets the decryption algorithm and key for decrypting the source object during multipart copy.
  2. Sets the encryption algorithm and key during part copy to enable the encryption for the target part.

SSE-C

Responses

Table 1 List of returned results

Type

Description

GetResult

Explanation:

SDK common results

Table 2 GetResult

Parameter

Type

Description

status

int

Explanation:

HTTP status code

Value range:

A status code is a group of digits ranging from 2xx (indicating successes) to 4xx or 5xx (indicating errors). It indicates the status of a response. For more information, see Status Code.

Default value:

None

reason

str

Explanation:

Reason description.

Default value:

None

errorCode

str

Explanation:

Error code returned by the OBS server. If the value of status is less than 300, this parameter is left blank.

Default value:

None

errorMessage

str

Explanation:

Error message returned by the OBS server. If the value of status is less than 300, this parameter is left blank.

Default value:

None

requestId

str

Explanation:

Request ID returned by the OBS server

Default value:

None

indicator

str

Explanation:

Error indicator returned by the OBS server.

Default value:

None

hostId

str

Explanation:

Requested server ID. If the value of status is less than 300, this parameter is left blank.

Default value:

None

resource

str

Explanation:

Error source (a bucket or an object). If the value of status is less than 300, this parameter is left blank.

Default value:

None

header

list

Explanation:

Response header list, composed of tuples. Each tuple consists of two elements, respectively corresponding to the key and value of a response header.

Default value:

None

body

object

Explanation:

Result content returned after the operation is successful. If the value of status is larger than 300, the value of body is null. The value varies with the API being called. For details, see Bucket-Related APIs (SDK for Python) and Object-Related APIs (SDK for Python).

Default value:

None

Code Examples

This example uploads and downloads an encrypted file using SSE-KMS.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from obs import ObsClient
from obs import PutObjectHeader, GetObjectHeader
from obs import SseKmsHeader
import os
import traceback

# Obtain an AK and SK pair using environment variables or import the AK and SK pair in other ways. Using hard coding may result in leakage.
# Obtain an AK and SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# (Optional) If you use a temporary AK and SK pair and a security token to access OBS, obtain them from environment variables.
# security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one in use.
server = "https://obs.ap-southeast-1.myhuaweicloud.com" 

# Create an obsClient instance.
# If you use a temporary AK and SK pair and a security token to access OBS, you must specify security_token when creating an instance.
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    put_headers = PutObjectHeader()
    # Specify the SSE-KMS encryption header for the object upload request.
    put_headers.sseHeader = SseKmsHeader.getInstance()

    bucketName = "examplebucket"
    # Specify an object name (the name displayed after the file is uploaded to the bucket).
    objectKey = "objectname"
    # Specify the full path of the file or folder to be uploaded, for example, aa/bb.txt or aa/.
    file_path = 'localfile'
    # Upload the object.
    resp = obsClient.putFile(bucketName, objectKey, file_path, headers=put_headers)


    # If status code 2xx is returned, the API is called successfully. Otherwise, the API call fails.
    if resp.status < 300:
        print('Put File Succeeded')
        print('requestId:', resp.requestId)
    else:
        print('Put File Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)

# ---------------------------------------------------------------------------------------------------------------------

    get_headers = GetObjectHeader()
    # Specify the SSE-KMS decryption header for the object download request.
    get_headers.sseHeader = SseKmsHeader.getInstance()

    bucketName = "examplebucket"
    objectKey = "objectname"
    # Specify the full path (localfile as an example) to which objects are downloaded. The full path contains the local file name.
    downloadPath = 'localfile'
    # Download the object.
    resp2 = obsClient.getObject(bucketName, objectKey, downloadPath, headers=get_headers)

    # If status code 2xx is returned, the API is called successfully. Otherwise, the API call fails.
    if resp2.status < 300:
        print('Get Object Succeeded')
        print('requestId:', resp2.requestId)
    else:
        print('Get Object Failed')
        print('requestId:', resp2.requestId)
        print('errorCode:', resp2.errorCode)
        print('errorMessage:', resp2.errorMessage)
except:
    print(traceback.format_exc())

This example uploads and downloads an encrypted file using SSE-C.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from obs import ObsClient
from obs import PutObjectHeader, GetObjectHeader
from obs import SseCHeader
import os
import traceback

# Obtain an AK and SK pair using environment variables or import the AK and SK pair in other ways. Using hard coding may result in leakage.
# Obtain an AK and SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# (Optional) If you use a temporary AK and SK pair and a security token to access OBS, obtain them from environment variables.
# security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one in use.
server = "https://obs.ap-southeast-1.myhuaweicloud.com" 

# Create an obsClient instance.
# If you use a temporary AK and SK pair and a security token to access OBS, you must specify security_token when creating an instance.
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    put_headers = PutObjectHeader()
    # Specify the SSE-C encryption header for the object upload request. encryption indicates the encryption method and key indicates the SSE-C key generated by the AES 256 algorithm.
    put_headers.sseHeader = SseCHeader(encryption='AES256', key='your sse-c key generated by AES-256 algorithm')

    bucketName = "examplebucket"
    # Specify an object name (the name displayed after the file is uploaded to the bucket).
    objectKey = "objectname"
    # Specify the full path of the file or folder to be uploaded, for example, aa/bb.txt or aa/.
    file_path = 'localfile'
    # Upload the object.
    resp = obsClient.putFile(bucketName, objectKey, file_path, headers=put_headers)

    # If status code 2xx is returned, the API is called successfully. Otherwise, the API call fails.
    if resp.status < 300:
        print('Put File Succeeded')
        print('requestId:', resp.requestId)
    else:
        print('Put File Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)

# ---------------------------------------------------------------------------------------------------------------------

    get_headers = GetObjectHeader()
    # Specify the SSE-C decryption header for an object download request. The key used here must be the one used for uploading the object.
    get_headers.sseHeader = SseCHeader(encryption='AES256', key='your sse-c key generated by AES-256 algorithm')

    bucketName = "examplebucket"
    objectKey = "objectname"
    # Specify the full path (localfile as an example) to which objects are downloaded. The full path contains the local file name.
    downloadPath = 'localfile'
    # Download the object.
    resp2 = obsClient.getObject(bucketName, objectKey, downloadPath, headers=get_headers)

    # If status code 2xx is returned, the API is called successfully. Otherwise, the API call fails.
    if resp2.status < 300:
        print('Get Object Succeeded')
        print('requestId:', resp2.requestId)
    else:
        print('Get Object Failed')
        print('requestId:', resp2.requestId)
        print('errorCode:', resp2.errorCode)
        print('errorMessage:', resp2.errorMessage)
except:
    print(traceback.format_exc())

Utilizamos cookies para mejorar nuestro sitio y tu experiencia. Al continuar navegando en nuestro sitio, tú aceptas nuestra política de cookies. Descubre más

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback