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

Updated on 2024-12-09 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

func (obsClient ObsClient) PutFile(input *PutFileInput) (output *PutObjectOutput, err error)

Supported APIs

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

Method in OBS SDK for Go

Description

Supported Encryption Method

ObsClient.PutObject

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 multipart copy to enable the encryption algorithm for the target part.

SSE-C

Code Examples

This example encrypts object example/objectname that is uploaded using streaming.

 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
package main
import (
    "crypto/md5"
    "encoding/base64"
    "fmt"
    "os"
    "strings"
    obs "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
)
func main() {
    //Obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways. Using hard coding may result in leakage.
    //Obtain an AK/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/SK pair and a security token to access OBS, you are advised not to use hard coding to reduce leakage risks. You can obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways.
    // securityToken := os.Getenv("SecurityToken")
    // Enter the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one currently in use.
    endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com"
    // Create an obsClient instance.
    // If you use a temporary AK/SK pair and a security token to access OBS, use the obs.WithSecurityToken method to specify a security token when creating an instance.
    obsClient, err := obs.New(ak, sk, endPoint/*, obs.WithSecurityToken(securityToken)*/)
    if err != nil {
        fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
    }
    input := &obs.PutObjectInput{}
    // Specify a bucket name.
    input.Bucket = "examplebucket"
    // Specify the object (example/objectname as an example) to upload.
    input.Key = "example/objectname"
    // Specify the content to upload.
    input.Body = strings.NewReader("Hello OBS")
    // Specify a server-side encryption header (obs.SseCHeader as an example).
    key := os.Getenv("Key")
    digest := md5.New()
    digest.Write([]byte(key))
    bodyHash := digest.Sum(nil)
    input.SseHeader = obs.SseCHeader{
        Encryption: "AES256",
        Key:        base64.StdEncoding.EncodeToString([]byte(key)), // 32byteslongsecretkeymustprovided
        KeyMD5:     base64.StdEncoding.EncodeToString(bodyHash),
    }
    // Upload you local file using streaming.
    output, err := obsClient.PutObject(input)
    if err == nil {
        fmt.Printf("Put object(%s) under the bucket(%s) successful!\n", input.Key, input.Bucket)
        fmt.Printf("RequestId:%s\n", output.RequestId)
        fmt.Printf("StorageClass:%s, ETag:%s\n",
            output.StorageClass, output.ETag)
        return
    }
    fmt.Printf("Put object(%s) under the bucket(%s) fail!\n", input.Key, input.Bucket)
    if obsError, ok := err.(obs.ObsError); ok {
        fmt.Println("An ObsError was found, which means your request sent to OBS was rejected with an error response.")
        fmt.Println(obsError.Error())
    } else {
        fmt.Println("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.")
        fmt.Println(err)
    }
}

This example downloads the encrypted object example/objectname using streaming.

 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
67
68
69
70
package main
import (
    "crypto/md5"
    "encoding/base64"
    "fmt"
    "os"
    obs "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
)
func main() {
    // Obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways. Using hard coding may result in leakage.
    // Obtain an AK/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/SK pair and a security token to access OBS, you are advised not to use hard coding to reduce leakage risks. You can obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways.
    // securityToken := os.Getenv("SecurityToken")
    // Enter the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one currently in use.
    endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com"
    // Create an obsClient instance.
    // If you use a temporary AK/SK pair and a security token to access OBS, use the obs.WithSecurityToken method to specify a security token when creating an instance.
    obsClient, err := obs.New(ak, sk, endPoint/*, obs.WithSecurityToken(securityToken)*/)
    if err != nil {
        fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
    }
    input := &obs.GetObjectInput{}
    // Specify a bucket name.
    input.Bucket = "examplebucket"
    // Specify the object (example/objectname as an example) to download.
    input.Key = "example/objectname"
    // Specify a server-side encryption header (obs.SseCHeader as an example).
    key := os.Getenv("Key")
    digest := md5.New()
    digest.Write([]byte(key))
    bodyHash := digest.Sum(nil)
    input.SseHeader = obs.SseCHeader{
        Encryption: "AES256",
        Key:        base64.StdEncoding.EncodeToString([]byte(key)), // 32byteslongsecretkeymustprovided
        KeyMD5:     base64.StdEncoding.EncodeToString(bodyHash),
    }
    // Download the object using streaming.
    output, err := obsClient.GetObject(input)
    if err == nil {
        // Close output.Body after using it, to avoid connection leakage.
        defer output.Body.Close()
        fmt.Printf("Get object(%s) under the bucket(%s) successful!\n", input.Key, input.Bucket)
        fmt.Printf("StorageClass:%s, ETag:%s, ContentType:%s, ContentLength:%d, LastModified:%s\n",
            output.StorageClass, output.ETag, output.ContentType, output.ContentLength, output.LastModified)
        // Read the object content.
        p := make([]byte, 1024)
        var readErr error
        var readCount int
        for {
            readCount, readErr = output.Body.Read(p)
            if readCount > 0 {
                fmt.Printf("%s", p[:readCount])
            }
            if readErr != nil {
                break
            }
        }
        return
    }
    fmt.Printf("List objects under the bucket(%s) fail!\n", input.Bucket)
    if obsError, ok := err.(obs.ObsError); ok {
        fmt.Println("An ObsError was found, which means your request sent to OBS was rejected with an error response.")
        fmt.Println(obsError.Error())
    } else {
        fmt.Println("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.")
        fmt.Println(err)
    }
}

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