Help Center> Object Storage Service> Node.js> FAQ> How Do I Specify Content-SHA256?
Updated on 2023-11-09 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:
// Import the OBS library.
// Use npm to install the client.
var ObsClient = require('esdk-obs-nodejs');
var crypto = require('crypto');
var fs = require('fs');
// Use the source code to install the client.
// var ObsClient = require('./lib/obs');

// Create an ObsClient instance.
const obsClient = new ObsClient({
    //Obtain an AK/SK pair using environment variables or import the 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.
    access_key_id: process.env.ACCESS_KEY_ID,
    secret_access_key: process.env.SECRET_ACCESS_KEY,
    //CN-Hong Kong is used here as an example. Replace it with the one in your actual situation.
    server: 'https://obs.ap-southeast-1.myhuaweicloud.com'
    
});

let filePath = 'D:\\example.xml'
let sha256 = crypto.createHash('sha256').update(fs.readFileSync(filePath, 'utf8'), 'utf8').digest('hex')

obsClient.putObject({
       Bucket : 'bucketname',
       Key : 'objectname',
       SourceFile : filePath,  // filePath indicates the path of the local file to be uploaded, which must have the file name included.
       ContentSha256 : sha256
}, (err, result) => {
       if(err){
              console.error('Error-->' + err);
       }else{
              console.log('Status-->' + result.CommonMsg.Status);
       }
});

Node.js SDK supports integrity check with both MD5 and SHA256 (recommended for security purposes).