Help Center> Object Storage Service> Java> FAQs (SDK for Java)> How Do I Specify Content-SHA256?
Updated on 2024-01-26 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 for uploading an object is as follows:

 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
71
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.PutObjectRequest;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.security.MessageDigest;

public class PutObjectWithSha256 {
    public static void main(String[] args) {
    // Hard-coded or plaintext AK/SK are risky. For security purposes, encrypt your AK/SK and store them in the configuration file or environment variables. In this example, the AK/SK are stored in environment variables for identity authentication. Before running this example, configure environment variables ACCESS_KEY_ID and SECRET_ACCESS_KEY_ID.
        // 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.
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");
        // (Optional) If you are using a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage.
        // Obtain an AK/SK pair and a security token using environment variables or import them in other ways.
        String securityToken = System.getenv("SECURITY_TOKEN");

        // Enter the endpoint corresponding to the bucket. Here uses CN North-Beijing4 as an example. Replace it with the one in use.
        // Obtain an endpoint using environment variables or import it in other ways.
        // String endPoint = System.getenv("ENDPOINT");
        String endPoint = "https://obs.cn-north-4.myhuaweicloud.com";

        // Create an ObsClient instance.
        try (ObsClient obsClient = new ObsClient(ak, sk, securityToken, endPoint)) {
            // This example uploads a local file to a bucket, with the content-sha256 header specified.

            String bucketName = "examplebucket";
            String objectKey = "exampleObjectKey";
            File localFile = new File("localFilePath");
            PutObjectRequest putObjectRequest = new PutObjectRequest();
            putObjectRequest.setBucketName(buketName);
            putObjectRequest.setObjectKey(objectKey);
            putObjectRequest.setFile(localFile);
            // Calculate SHA256 of the file.
            InputStream fis = Files.newInputStream(localFile.toPath());
            byte[] buffer = new byte[1024];
            MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
            for (int numRead = 0; (numRead = fis.read(buffer)) > 0; ) {
                sha256.update(buffer, 0, numRead);
            }
            fis.close();
            // Convert the SHA256 value to a hexadecimal number.
            StringBuilder sha256Builder = new StringBuilder();
            for (byte aB : sha256.digest()) {
                sha256Builder.append(String.format("%02x", aB));
            }
            // Add the SHA256 to the user-defined header.
            putObjectRequest.addUserHeaders("x-obs-content-sha256", sha256Builder.toString());
            obsClient.putObject(putObjectRequest);
            System.out.println("PutObjectWithSha256 successfully");
        } catch (ObsException e) {
            System.out.println("PutObjectWithSha256 failed");
            // Request failed. Print the HTTP status code.
            System.out.println("HTTP Code:" + e.getResponseCode());
            // Request failed. Print the server-side error code.
            System.out.println("Error Code:" + e.getErrorCode());
            // Request failed. Print the detailed error information.
            System.out.println("Error Message:" + e.getErrorMessage());
            // Request failed. Print the request ID.
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("PutObjectWithSha256 failed");
            // Print other error information.
            e.printStackTrace();
        }
    }
}

OBS SDK for Java supports integrity check with both MD5 and SHA256 (SHA256 is recommended for its higher security).