Untitled

 avatar
unknown
javascript
4 years ago
2.7 kB
90
Indexable
const CryptoJS = require("crypto-js");
const request = require("request");
require("dotenv").config();
const parser = require("xml2json");
const fs = require("fs");

const account = process.env.ACCOUNT_NAME || "";
const key = process.env.ACCOUNT_KEY || "";
const containerName = "demo";
const blobName = "dummyfile.txt";

var strTime = new Date().toUTCString();

string_params = {
  verb: "PUT",
  "Content-Encoding": "",
  "Content-Language": "",
  "Content-Length": "",
  "Content-MD5": "",
  "Content-Type": "application/octet-stream",
  Date: "",
  "If-Modified-Since": "",
  "If-Match": "",
  "If-None-Match": "",
  "If-Unmodified-Since": "",
  Range: "",
  CanonicalizedHeaders:
    "x-ms-blob-type:BlockBlob" +
    "\nx-ms-date:" +
    strTime +
    "\nx-ms-version:" +
    "2018-03-28\n",
  CanonicalizedResource: `/${account}/${containerName}/${blobName}`,
};

var strToSign =
  string_params["verb"] +
  "\n" +
  string_params["Content-Encoding"] +
  "\n" +
  string_params["Content-Language"] +
  "\n" +
  string_params["Content-Length"] +
  "\n" +
  string_params["Content-MD5"] +
  "\n" +
  string_params["Content-Type"] +
  "\n" +
  string_params["Date"] +
  "\n" +
  string_params["If-Modified-Since"] +
  "\n" +
  string_params["If-Match"] +
  "\n" +
  string_params["If-None-Match"] +
  "\n" +
  string_params["If-Unmodified-Since"] +
  "\n" +
  string_params["Range"] +
  "\n" +
  string_params["CanonicalizedHeaders"] +
  string_params["CanonicalizedResource"];

var secret = CryptoJS.enc.Base64.parse(key);
var hash = CryptoJS.HmacSHA256(strToSign, secret);
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
var auth = `SharedKey ${account}:` + hashInBase64;

const options = {
  url: `https://${account}.blob.core.windows.net/${containerName}/${blobName}`,
  headers: {
    Authorization: auth,
    "x-ms-date": strTime,
    "x-ms-version": "2018-03-28",
    "x-ms-blob-type": "BlockBlob",
    "Content-Type": "application/octet-stream",
  },
};

function callback(error, response, body) {
  console.log(response.statusCode);
  console.log(response.statusMessage);
  console.log(response.headers);
}

request(options, callback).pipe(fs.createWriteStream(`${__dirname}/README.md`));

//////////////////////////////////////// RESULT /////////////////////////////////////

// 403
// Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
// {
//   'content-length': '709',
//   'content-type': 'application/xml',
//   server: 'Microsoft-HTTPAPI/2.0',
//   'x-ms-request-id': '58b6c810-201e-0035-69d4-10a44f000000',
//   'x-ms-error-code': 'AuthenticationFailed',
//   date: 'Thu, 04 Mar 2021 08:56:35 GMT',
//   connection: 'close'
// }
Editor is loading...