Help Center/ Object Storage Service/ SDK Reference/ Node.js/ FAQs (SDK for Node.js)/ How Do I Specify Content-SHA256? (SDK for Node.js)
Updated on 2024-11-13 GMT+08:00

How Do I Specify Content-SHA256? (SDK for Node.js)

The x-obs-content-sha256 header can be carried during object or part upload. Its value is a hexadecimal representation of the SHA-256 value of the request body calculated using Hex(SHA256Hash(<payload>). The server verifies the calculated value for an integrity check. This might affect the performance but is still recommended for security purposes. The 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);
       }
});

SDK for Node.js supports both MD5 and SHA256 verification, but SHA256 is recommended for security reasons.