Help Center/ Object Storage Service/ SDK Reference/ Java/ Server-Side Encryption (SDK for Java)/ Code Examples for Server-Side Encryption (SDK for Java)
Updated on 2024-06-18 GMT+08:00

Code Examples for Server-Side Encryption (SDK for Java)

If you have any questions during development, post them on the Issues page of GitHub.

Code Example: Encrypting (SSE-C) and Uploading an Object

The following code shows an example of encrypting an object with SSE-C before uploading it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Enter the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one in your actual situation.
String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
// Hard-coded or plaintext access keys (AK/SK) are risky. For security purposes, encrypt your access keys and store them in the configuration file or environment variables. In this example, access keys are stored in the environment variables for identity authentication. Before running the code in 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");
// Create an ObsClient instance.
ObsClient obsClient = new ObsClient(ak, sk, endPoint);

PutObjectRequest request = new PutObjectRequest();
request.setBucketName("bucketname");
request.setObjectKey("objectname");
request.setFile(new File("localfile"));

HashMap<String, String> userHeaders = new HashMap<>();
userHeaders.put("x-obs-server-side-encryption-customer-algorithm","AES256");
//The key for encrypting objects when SSE-C is used. Its value is a Base64-encoded 256-bit key.
userHeaders.put("x-obs-server-side-encryption-customer-key","your-encryption-customer-key");
userHeaders.put("x-obs-server-side-encryption-customer-key-MD5",
                    ServiceUtils.toBase64(ServiceUtils.computeMD5Hash(ServiceUtils.fromBase64("your-encryption-customer-key"))));            request.setUserHeaders(userHeaders);
HeaderResponse response = obsClient.putObject(request);
System.out.println("response:"+response.getRequestId());

Code Example: Encrypting (SSE-OBS) and Uploading an Object

The following code shows an example of using the x-obs-server-side-encryption:AES256 header to encrypt an object with SSE-OBS before uploading it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// Enter the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one in your actual situation.
String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
// Hard-coded or plaintext access keys (AK/SK) are risky. For security purposes, encrypt your access keys and store them in the configuration file or environment variables. In this example, access keys are stored in the environment variables for identity authentication. Before running the code in 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");
// Create an ObsClient instance.
ObsClient obsClient = new ObsClient(ak, sk, endPoint);
// Specify the bucket name, object name, and local file path.
PutObjectRequest request = new PutObjectRequest();
request.setBucketName("BucketName");
request.setObjectKey("ObjectKey");
request.setFile(new File("LocalFilePath"));
// Add a user-defined header to use SSE-OBS.
HashMap<String, String> userHeaders = new HashMap<>();
userHeaders.put("x-obs-server-side-encryption","AES256");
request.setUserHeaders(userHeaders);
HeaderResponse response = obsClient.putObject(request);

Code Example: Decrypting and Downloading an Object

The following code shows an example of downloading an object encrypted with 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
66
67
68
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.internal.utils.ServiceUtils;
import com.obs.services.model.GetObjectRequest;
import com.obs.services.model.ObsObject;
import java.util.HashMap;
import java.util.Map;

public class SseCGetObject{
    public static void main(String[] args) {
        // Hard-coded or plaintext AK and SK are risky. For security purposes, encrypt your AK and SK and store them in the configuration file or environment variables. In this example, the AK and SK are stored in environment variables for identity authentication.
        //Before running the code in 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. CN-Hong Kong is used here as an example. Replace it with the one in your actual situation.
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // Create an ObsClient instance and use the permanent AK/SK pair to initialize the client.
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);
        // Use the temporary AK/SK pair and security token to initialize the client.
        // ObsClient obsClient = new ObsClient(ak, sk, securityToken, endPoint);

        try {
            // Call APIs to perform operations, for example, downloading an encrypted object.
            GetObjectRequest request=new GetObjectRequest("bucketname","objectname");
            // Set the SSE-C decryption algorithm.
            HashMap<String, String> userHeaders=new HashMap<>();
            userHeaders.put("x-obs-server-side-encryption-customer-algorithm","AES256");
            The header indicates the key used to encrypt objects in SSE-C mode. The header value is a Base64-encoded 256-bit key.
            userHeaders.put("x-obs-server-side-encryption-customer-key","your-encryption-customer-key");
            userHeaders.put("x-obs-server-side-encryption-customer-key-MD5",
                    ServiceUtils.toBase64(ServiceUtils.computeMD5Hash(ServiceUtils.fromBase64("your-encryption-customer-key"))));
            request.setUserHeaders(userHeaders);
            ObsObject obsObject=obsClient.getObject(request);
            // You can use other methods to read streams.
            System.out.println(obsObject.getObjectContent());
        }
        catch(ObsException e) {
            System.out.println("putObject 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 error details.
            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());
            Map<String, String> headers=e.getResponseHeaders();
            if(headers!=null){
                Check all map entries and print all headers with errors reported.
                for(Map.Entry<String, String> header:headers.entrySet()){
                    if(header.getKey().contains("error")){
                        System.out.println(header.getKey()+":"+header.getValue());
                    }
                }
            }
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("putObject failed");
            // Print other error information.
            e.printStackTrace();
        }
    }
}

When you download an object encrypted with SSE-OBS or obtain the metadata of such an object, the object is automatically decrypted and no encryption-related headers are required. For details, see Downloading an Object - Streaming (SDK for Java) and Obtaining Object Metadata (SDK for Java).