Help Center/ Object Storage Service/ SDK Reference/ Go/ FAQ (SDK for Go)/ How Do I Specify Content-SHA256?
Updated on 2024-06-21 GMT+08:00

How Do I Specify Content-SHA256?

You can upload the x-obs-content-sha256 header when uploading an object or a part. The value of this header is the hexadecimal value converted from the SHA256 value of the request body and is calculated from Hex(SHA256Hash(<payload>). The server calculates and verifies the SHA256 value of the message body in the request with x-obs-content-sha256 included, which may make performance deteriorate, but is recommended for security purposes. Sample code is as follows:

This example deletes the asynchronous fetch policy of bucket examplebucket.

 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
package main
import (
    "crypto/sha256"
    "fmt"
    "io"
    "os"
    obs "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
)
func sha256File(path string) string {
    file, err := os.Open(path) // Open the file for reading
    if err != nil {
        panic(err)
    }
    defer file.Close() // Be sure to close your file!
    hash := sha256.New() // Use the Hash in crypto/sha256
    if _, err := io.Copy(hash, file); err != nil {
        panic(err)
    }
    return fmt.Sprintf("%x", hash.Sum(nil))
}
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), obs.WithSignature(obs.SignatureObs))
    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 download.
    input.Key = "example/objectname"
    filePath := "localfile"
    fd, _ := os.Open(filePath)
    defer fd.Close()
    input.Body = fd
    // Upload you local file using streaming.
    output, err := obsClient.PutObject(input, obs.WithCustomHeader("x-obs-content-sha256", sha256File(filePath)))
    if err == nil {
        fmt.Printf("Put object(%s) under the bucket(%s) successful!\n", input.Key, input.Bucket)
        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)
    }
}

OBS SDK for Go supports integrity check with both MD5 and SHA256 (SHA256 is recommended for security purposes).