English 中文(简体)
我的支票 i 在javascript中为S3管理上载荷制造,总是错失。
原标题:My CheckSumSHA256 i create in javascript for S3 ManagedUpload is always wrong

sha256 is the SHA256 Hash of a file. I use then btoa(256) to base64 it.

The result is always InvalidRequest: Value for x-amz-checksum-sha256 header is invalid.

AWS 文件说,

ChecksumSHA256 — (String) The base64-encoded, 256-bit SHA-256 digest of the object. This will only be present if it was uploaded with the object. With multipart uploads, this may not be a checksum value of the object. For more information about how checksums are calculated with multipart uploads, see Checking object integrity in the Amazon S3 User Guide. Checking object integrity - Amazon Simple Storage Service Verify the integrity of objects uploaded and downloaded to Amazon S3.

let sha256conv = btoa(sha256);

const params = {
        Bucket: process.env.BUCKET,
        Key: path.basename(task.file),
        Body: fileData,
        ContentType: ContentType ||  application/octet-stream ,
        CacheControl: "max-age=172800",
        ChecksumAlgorithm:  sha256 ,
        ChecksumSHA256: sha256conv
    
    };

const upload = new AWS.S3.ManagedUpload({
        service: s3,
        params
    });

第256页就是这样:

export async function getFileSha256(fileName, fileSize, onProgress) {
    return new Promise((resolve, reject) => {
        const hash = crypto.createHash( sha256 );

// change to  binary  if you want a binary hash.
        hash.setEncoding( hex );
        const bar1 = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);
        bar1.start(fileSize, 0);

        const fd = fs.createReadStream(fileName);

        fd.on( data , async chunk => {
            let processedBytes = bar1.value + chunk.length;
            bar1.update(processedBytes);
            await onProgress(processedBytes)
        })

        fd.on( end , function () {
            bar1.stop();
            hash.end();
            return resolve(hash.read())
        });

// read all file and pipe it (write it) to the hash object
        fd.pipe(hash);
    });
}

问题回答

SHA-256 takes bytes (not text) as input and produces bytes (not text) as output. Of course, dealing with raw bytes is not always convenient so checksum bytes are often somehow converted to text, and there re multiple ways to do so.

Im no Javaend 专家,但似乎在计算SHA-256检查时,你自动将其编码为Hex:

hash.setEncoding( hex );

接着请在Base64 :

let sha256conv = btoa(sha256);

因此,整个链条有:bytes。 ->Hex ->Base64

如果你将这个问题改为bytes,则可以解决这个问题。 ->Base64 by using hash.setEncoding( binary )

      (async()=>{
      
            var message   =  helloworld ;
            var hex       = await digest(message);
            var b64       = b64encode(hex);
            
            console.log(b64);
        
      })();      

      
      async function digest(message) {
      
            var msgUint8      = new TextEncoder().encode(message);                            // encode as (utf-8) Uint8Array
            var hashBuffer    = await crypto.subtle.digest( SHA-256 ,msgUint8);               // hash the message
            var hashArray     = Array.from(new Uint8Array(hashBuffer));                       // convert buffer to byte array
            var hashHex       = hashArray.map(b=>b.toString(16).padStart(2, 0 )).join(  );    // convert bytes to hex string
            return hashHex;
        
      }//digest


        function b64encode(input){
        
              input         = utf8_encode(input);
              var output    =   ;
              
              var keyStr    =  ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/= ;
              
              var i         = 0;              
              while(i<input.length){
              
                      var chr1    = input.charCodeAt(i++);
                      var chr2    = input.charCodeAt(i++);
                      var chr3    = input.charCodeAt(i++);
                      var enc1    = chr1>>2;
                      var enc2    = ((chr1&3)<<4)|(chr2>>4);
                      var enc3    = ((chr2&15)<<2)|(chr3>>6);
                      var enc4    = chr3&63;
                      
                      if(isNaN(chr2)){
                            enc3    = enc4    = 64;
                      }else{
                            if(isNaN(chr3)){
                                  enc4    = 64;
                            }
                      }
                      
                      output    = output                +
                                  keyStr.charAt(enc1)   +
                                  keyStr.charAt(enc2)   +
                                  keyStr.charAt(enc3)   +
                                  keyStr.charAt(enc4)
                      ;
                      
              }//while
              
              return output;
              
        }//encode

        function utf8_encode(string){
        
              string        = string.replace(/
/g, 
 );
              var utftext   = "";
              
              for(var n=0;n<string.length;n++){
              
                    var c   = string.charCodeAt(n);
                    if(c<128){
                        utftext  += String.fromCharCode(c);
                    }else{
                          if((c>127)&&(c<2048)){
                                utftext += String.fromCharCode((c>>6)|192);
                                utftext += String.fromCharCode((c&63)|128);
                          }else{
                                utftext += String.fromCharCode((c>>12)|224);
                                utftext += String.fromCharCode(((c>>6)&63)|128);
                                utftext += String.fromCharCode((c&63)|128);
                          }
                    }
                    
              }//for
              
              return utftext;
              
        }//utf8_encode

该法典产生的产出与产出相同。

https://codebeauties.org/sha256-hash-generator”rel=“nofollow noreferer”>sha-256h generator

Base64 encode

希望这一帮助





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签