tencent cloud

Cloud Object Storage

Data Security Enhancement

PDF
Focus Mode
Font Size
Last updated: 2026-04-16 11:30:53

Introduction

This article describes how to enhance data security from client to cloud by implementing transport encryption, storage encryption, integrity verification, and access policy control through the COS SDK.

Feature Description

In the digital era, the importance of data security is undoubtedly paramount. Whether it's user privacy information or core business assets, any leakage, tampering, or unauthorized access during transmission or storage may lead to business abnormalities and even greater losses.
COS SDK establishes an end-to-end, full-chain protection framework by enhancing transport protocol security, CRC64 download verification, MD5 upload verification, COS server-side encryption, and temporary key permission control, ensuring comprehensive data security for your operations.

Improvement Methods

Method 1: End-To-End Encryption, Comprehensive Protection Throughout The Entire Process From Transmission To Storage

1. Transport Security

HTTPS mutual authentication, also known as two-way TLS authentication or client authentication, is a secure communication protocol where both the server and client must verify each other's identity. In standard HTTPS, the server primarily authenticates itself to the client (via a server certificate), establishing a secure, encrypted communication channel. Mutual authentication builds upon this by requiring the client to also provide a certificate for the server to validate its identity. This approach is commonly used in systems requiring high security to ensure both communicating parties are trusted.
COS enhances its standard HTTPS by adding server-side verification of client certificates, ensuring only authorized devices can access COS services and effectively preventing man-in-the-middle attacks. The detailed steps are as follows:




Step 1: Prepare an Access Server Supporting Mutual Authentication

Taking Nginx as an example, mutual authentication can be enabled with the configuration shown in the figure below. For methods to enable mutual authentication on other platforms, see the specific documentation for the respective platform.
As shown in the figure below, record the domain host with mutual authentication enabled and the client certificate for Step 2.




Step 2: Configure Client-Side Mutual Authentication Support in the COS SDK

Note:
COS iOS SDK version must be greater than or equal to 6.4.8, COS Android SDK version must be greater than or equal to 5.9.35.
Android
iOS
// Bucket region abbreviation, for example, the Guangzhou region is ap-guangzhou
String region = "COS_REGION" ;
// Byte array of the tls client certificate, which must be in BKS format
byte[] certificateBytes;
// Password for the BKS file. If your BKS file has no password, pass null
String password = "123456";
// Server host configured with mutual authentication
String dualCheckHost = "dual-check.myEdgeOne.com";
CosXmlServiceConfig cosXmlServiceConfig = new CosXmlServiceConfig.Builder()
.isHttps(true)
.setRegion(region)
.setHost(dualCheckHost)
// Set the tls client certificate
.setClientCertificate(certificateBytes, password)
.builder();
CosXmlService cosXmlService = new CosXmlService(context, cosXmlServiceConfig,
credentialProvider);
QCloudServiceConfiguration* configuration = [QCloudServiceConfiguration new];
QCloudCOSXMLEndPoint* endpoint = [[QCloudCOSXMLEndPoint alloc] init];

// Replace with your region. The region to which the created bucket belongs can be viewed in the console at https://console.tencentcloud.com/cos5/bucket
// For a list of all regions supported by COS, see https://www.tencentcloud.com/document/product/436/6224?from_cn_redirect=1
endpoint.regionName = @"COS_REGION";
// Use HTTPS
endpoint.useHTTPS = true;
configuration.endpoint = endpoint;

// Configure the client p12 certificate.
NSString *path = [[NSBundle mainBundle] pathForResource:@"client" ofType:@"p12"];
NSData *p12Data = [NSData dataWithContentsOfFile:path];
configuration.clientCertificateData = p12Data;
// Configure the certificate password
configuration.password = @"123456";

// Example of initializing the COS service
[QCloudCOSXMLService registerDefaultCOSXMLWithConfiguration:configuration];
[QCloudCOSTransferMangerService registerDefaultCOSTransferMangerWithConfiguration:
configuration];

2. Storage Security

Server-Side Encryption (SSE-COS/SSE-KMS/SSE-C) supports applying data encryption protection policies at the object level before data is written to disks in the data center, and automatically decrypts data upon access. The encryption and decryption processes are completed entirely on the server side. This server-side encryption feature effectively protects data at rest. For details, see Android Server-Side Encryption and iOS Server-Side Encryption.
Android
iOS
// Prepare TransferManager
TransferConfig transferConfig = new TransferConfig.Builder()
.build();
TransferManager transferManager = new TransferManager(cosXmlService,
transferConfig);

// Use server-side encryption (SSE-COS) with COS-managed encryption keys to protect data
PutObjectRequest putObjectRequestCos = new PutObjectRequest(bucket, cosPath, srcPath);
putObjectRequestCos.setCOSServerSideEncryption();
COSXMLUploadTask cosxmlUploadTaskCos = transferManager.upload(putObjectRequestCos, uploadId);

// Set server-side encryption (SSE-KMS) using customer-provided master keys to protect data
String customKey = "Customer Master Key CMK";
String encryptContext = "Encryption Context";
PutObjectRequest putObjectRequestKms = new PutObjectRequest(bucket, cosPath, srcPath);
try {
putObjectRequestKms.setCOSServerSideEncryptionWithKMS(customKey, encryptContext);
} catch (CosXmlClientException e) {
e.printStackTrace();
}
COSXMLUploadTask cosxmlUploadTaskKms = transferManager.upload(putObjectRequestKms, uploadId);

// Set server-side encryption (SSE-C) using customer-provided encryption keys to protect data
String customKeyC = "Server-Side Encryption Key";
PutObjectRequest putObjectRequestC = new PutObjectRequest(bucket, cosPath, srcPath);
try {
putObjectRequestC.setCOSServerSideEncryptionWithCustomerKey(customKey);
} catch (CosXmlClientException e) {
e.printStackTrace();
}

// Upload object
COSXMLUploadTask cosxmlUploadTaskC = transferManager.upload(putObjectRequestC, uploadId);
// 1. Use server-side encryption (SSE-COS) with COS-managed encryption keys to protect data
QCloudCOSXMLUploadObjectRequest *request = [QCloudCOSXMLUploadObjectRequest new];
[request setCOSServerSideEncyption];

// 2. Use server-side encryption (SSE-C) with customer-provided encryption keys to protect data
QCloudCOSXMLUploadObjectRequest *request = [QCloudCOSXMLUploadObjectRequest new];
NSString *customKey = @"123456qwertyuioplkjhgfdsazxcvbnm";
[request setCOSServerSideEncyptionWithCustomerKey:customKey];

// 3. Use server-side encryption (SSE-KMS) with KMS-managed encryption keys to protect data
QCloudCOSXMLUploadObjectRequest *request = [QCloudCOSXMLUploadObjectRequest new];
NSString *customKey = @"123456qwertyuioplkjhgfdsazxcvbnm";
NSString *arrJsonStr = @"{\\"key\\":\\"value\\"}";
[request setCOSServerSideEncyptionWithKMSCustomKey:customKey jsonStr:arrJsonStr];

Method 2: Data Integrity Assurance, Dual Verification Mechanism for Upload and Download

1. MD5 Upload Verification

The client automatically calculates and carries the MD5 checksum of the object during upload, transmitting it to the server via the Content-MD5 Request Header. The COS server performs real-time consistency verification upon receipt to prevent data tampering or corruption caused by network packet loss or hijacking. If the MD5 checksum fails verification, the upload fails and returns a 400 Bad Request exception in the failure callback. For details, see Uploading Objects in Android and Uploading Objects in iOS.
Android
iOS
// Initialize TransferManager
TransferConfig transferConfig = new TransferConfig.Builder()
.build();
TransferManager transferManager = new TransferManager(cosXmlService,
transferConfig);

// Upload object
String srcPath = new File(context.getCacheDir(), "exampleobject.txt")
.toString(); // Absolute path of the local file
COSXMLUploadTask cosxmlUploadTask = transferManager.upload("examplebucket-1250000000", "exampleobject.txt",
srcPath, null);
QCloudCOSXMLUploadObjectRequest* put = [QCloudCOSXMLUploadObjectRequest new];
NSURL* url = [NSURL fileURLWithPath:@"File URL"];
// Bucket name, which consists of BucketName-Appid, can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket
put.bucket = @"examplebucket-1250000000";
// Object key, which is the full path of the object on COS. If including a directory, the format should be "video/xxx/movie.mp4"
put.object = @"exampleobject";
// The content of the object to be uploaded. You can pass in a variable of type NSData* or NSURL*
put.body = url;
// Monitor upload progress
[put setSendProcessBlock:^(int64_t bytesSent,
int64_t totalBytesSent,
int64_t totalBytesExpectedToSend) {
// bytesSent The number of bytes to be sent this time (a large file may need to be sent in multiple parts)
// totalBytesSent The number of bytes sent
// totalBytesExpectedToSend The total number of bytes to be sent in this upload (which is the size of a single file)
}];
// Monitor upload result
[put setFinishBlock:^(QCloudUploadObjectResult *result, NSError *error) {
// Obtain the download link of the uploaded file from result.location in the upload result
NSString * fileUrl = result.location;
// Obtain the file crc64
NSString * crc64 = [[result __originHTTPURLResponse__].allHeaderFields valueForKey:@"x-cos-hash-crc64ecma"];
}];
[put setInitMultipleUploadFinishBlock:^(QCloudInitiateMultipartUploadResult *
multipleUploadInitResult,
QCloudCOSXMLUploadObjectResumeData resumeData) {
// After the multipart upload initialization is completed, this block will be called back, where you can obtain resumeData and uploadid
NSString* uploadId = multipleUploadInitResult.uploadId;
}];
[[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:put];

2. CRC64 Download Verification

The client verifies whether the returned CRC64 value matches the locally calculated value when downloading objects from COS, ensuring the integrity of the downloaded content and preventing data errors caused by network jitter or storage media failures.
COS SDK enables crc64 verification by default in the advanced download method of the new version:
The verification process uses asynchronous segmented verification to reduce the time consumption caused by crc64 verification of large objects.
After a verification failure, the system will retry three times. If the download still fails after retries, it will terminate and throw a crc64 verification failure exception in the failure callback.
When resuming an interrupted download, the system first verifies whether the locally downloaded object matches the crc64 result. If the object is inconsistent, it re-downloads the object to avoid completing the entire download only to discover a mismatch.
For more languages, see CRC64 Verification.
Android
iOS
// Initialize TransferManager
TransferConfig transferConfig = new TransferConfig.Builder()
.build();
TransferManager transferManager = new TransferManager(cosXmlService,
transferConfig);

COSXMLDownloadTask cosxmlDownloadTask =
transferManager.download(context,
"examplebucket-1250000000", "exampleobject.txt", context.getExternalCacheDir().toString(), "exampleobject.txt");
QCloudCOSXMLDownloadObjectRequest * request = [QCloudCOSXMLDownloadObjectRequest new];

// Bucket name, which consists of BucketName-Appid, can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket
request.bucket = @"examplebucket-1250000000";

// Object key, which is the full path of the object on COS. If including a directory, the format should be "video/xxx/movie.mp4"
request.object = @"exampleobject";

// Set the download path URL. If specified, the object will be downloaded to the designated path.
request.downloadingURL = [NSURL fileURLWithPath:@"Local File Path"];

// The size of the locally downloaded object. If downloading from the beginning, do not specify this value.
request.localCacheDownloadOffset = 100;

// Monitor download result
[request setFinishBlock:^(id outputObject, NSError *error) {
// outputObject contains all the response http headers
NSDictionary* info = (NSDictionary *) outputObject;
// If no download path is specified, obtain the downloaded NSData in the following manner.
NSData * data = [outputObject __originHTTPResponseData__];
}];

// Monitor download progress
[request setDownProcessBlock:^(int64_t bytesDownload,
int64_t totalBytesDownload,
int64_t totalBytesExpectedToDownload) {

// bytesDownload Bytes added
// totalBytesDownload Total bytes received during this download
// totalBytesExpectedToDownload Target bytes for this download
}];

[[QCloudCOSTransferMangerService defaultCOSTransferManager] DownloadObject:request];

Method 3: Temporary Key Permission Control and Fine-Grained Permission Management

1. Principle of Least Privilege

Note:
When permissions are granted, it is recommended to strictly adhere to the principle of least privilege. Limit users to performing restricted operations (for example, authorizing action:GetObject) and accessing restricted resources (for example, authorizing resource:examplebucket-1250000000/exampleobject.txt). To avoid granting excessive permissions that may lead to unintended overreach and pose data security risks, we strongly advise against granting users permissions to access all resources (such as resource:*) or perform all operations (such as action:*). For details, see Principle of Least Privilege.
We strongly recommend that you do not set the bucket to public read-write, as this poses a high security risk.
Potential data security risks include:
Data Leakage: Granting users permission to download specific resources, such as examplebucket-1250000000/data/config.json and examplebucket-1250000000/video/. However, if the permission policy is configured as examplebucket-1250000000/*, all objects in the bucket will be downloadable. This leads to overreach operations and potential leakage of unexpected data.
Data Overwrite: Granting users permission to upload resources, such as examplebucket-1250000000/data/config.json and examplebucket-1250000000/video/. However, if the permission policy is configured as examplebucket-1250000000/*, all objects in the bucket will be uploadable. This leads to overreach operations and potential overwriting of unexpected objects. To mitigate this risk, in addition to adhering to the principle of least privilege, you can enable version control to retain all historical versions of data for traceability.
Permission Leakage: Granting users permission to list objects in a bucket (cos:GetBucket). However, if the permission policy is configured as cos:*, all operations on the bucket will be permitted, including reauthorizing the bucket, deleting objects, and deleting the bucket, which poses significant risks to your data.

2. Server-Side Generates Cos Key

In Web or client upload scenarios, there is a risk that objects may be overwritten if their names are specified by the client.
The key measure to prevent objects from being overwritten is having the server-side determine the upload path.




3. Upload Limit Policy

Through the policy of temporary credentials, multiple constraints can be imposed on upload operations.
Restrict the size of uploaded objects
Scenario 1: For PutObject uploads, this is achieved by setting the numeric_less_than_equal condition in the policy of sts temporary credentials.
condition: {
// Restrict uploaded objects to less than 5MB
'numeric_less_than_equal': {
'cos:content-length': 5 * 1024 * 1024
},
}
Scenario 2: For PostObject uploads, this is achieved by setting the content-length-range condition in the conditions of the signature policy.
var policy = JSON.stringify({
...
conditions: [
['content-length-range', 1, 5 * 1024 * 1024], // Restrict the size range of uploaded objects, e.g., 1 - 5MB
],
});
Restrict the type of uploaded objects
Scenario 1: For PutObject uploads, this is achieved by setting the string_like condition in the policy of sts temporary credentials.
condition: {
// Restrict the content-type of uploaded objects to image types
'string_like': {
'cos:content-type': 'image/*'
}
}
Scenario 2: For PostObject uploads, this is achieved by setting the $Content-Type condition in the conditions of the signature policy.
var policy = JSON.stringify({
...
conditions: [
// Restrict the content-type of uploaded objects to image types
['starts-with', '$Content-Type', 'image/*'],
],
});

4. Hands-on Tutorial

For the features of least privilege for temporary keys, server-side generation of Cos Key, and upload restriction policy, we provide practical tutorials in various languages. Please refer to Android Object Upload Practical Tutorial, iOS Object Upload Practical Tutorial, and JavaScript Object Upload Practical Tutorial. These include sample code for generating permission-controlled temporary keys on the server side and using temporary keys for client-side uploads.

Best Practices

To maximize security capabilities, developers are advised to refer to the following practices:
1. Enable HTTPS mutual authentication: For sensitive business scenarios (such as financial, medical, and vehicle systems), it is recommended to enable HTTPS mutual authentication and regularly rotate client certificates.
2. Key lifecycle management: If using SSE-KMS custom encryption, it is recommended to regularly rotate keys through the Tencent Cloud Key Management System (KMS) and strictly control access permissions.
3. Temporary key permission control: Manage object access permissions according to the recommended principle of least privilege, along with operations such as overwrite prevention and conditional restrictions.

Help and Support

Was this page helpful?

Help us improve! Rate your documentation experience in 5 mins.

Feedback